babylon.max.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. /** @hidden */
  441. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  442. // Rebuild shaders source code
  443. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  444. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  445. vertexCode = prefix + vertexCode;
  446. fragmentCode = prefix + fragmentCode;
  447. // Number lines of shaders source code
  448. var i = 2;
  449. var regex = /\n/gm;
  450. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  451. i = 2;
  452. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  453. // Dump shaders name and formatted source code
  454. if (this.name.vertexElement) {
  455. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  456. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  457. }
  458. else if (this.name.vertex) {
  459. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  460. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  461. }
  462. else {
  463. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  464. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  465. }
  466. };
  467. ;
  468. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  469. var preparedSourceCode = this._processPrecision(sourceCode);
  470. if (this._engine.webGLVersion == 1) {
  471. callback(preparedSourceCode);
  472. return;
  473. }
  474. // Already converted
  475. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  476. callback(preparedSourceCode.replace("#version 300 es", ""));
  477. return;
  478. }
  479. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  480. // Remove extensions
  481. // #extension GL_OES_standard_derivatives : enable
  482. // #extension GL_EXT_shader_texture_lod : enable
  483. // #extension GL_EXT_frag_depth : enable
  484. // #extension GL_EXT_draw_buffers : require
  485. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  486. var result = preparedSourceCode.replace(regex, "");
  487. // Migrate to GLSL v300
  488. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  489. result = result.replace(/attribute[ \t]/g, "in ");
  490. result = result.replace(/[ \t]attribute/g, " in");
  491. if (isFragment) {
  492. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  494. result = result.replace(/texture2D\s*\(/g, "texture(");
  495. result = result.replace(/textureCube\s*\(/g, "texture(");
  496. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  497. result = result.replace(/gl_FragColor/g, "glFragColor");
  498. result = result.replace(/gl_FragData/g, "glFragData");
  499. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  500. }
  501. callback(result);
  502. };
  503. Effect.prototype._processIncludes = function (sourceCode, callback) {
  504. var _this = this;
  505. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  506. var match = regex.exec(sourceCode);
  507. var returnValue = new String(sourceCode);
  508. while (match != null) {
  509. var includeFile = match[1];
  510. // Uniform declaration
  511. if (includeFile.indexOf("__decl__") !== -1) {
  512. includeFile = includeFile.replace(/__decl__/, "");
  513. if (this._engine.supportsUniformBuffers) {
  514. includeFile = includeFile.replace(/Vertex/, "Ubo");
  515. includeFile = includeFile.replace(/Fragment/, "Ubo");
  516. }
  517. includeFile = includeFile + "Declaration";
  518. }
  519. if (Effect.IncludesShadersStore[includeFile]) {
  520. // Substitution
  521. var includeContent = Effect.IncludesShadersStore[includeFile];
  522. if (match[2]) {
  523. var splits = match[3].split(",");
  524. for (var index = 0; index < splits.length; index += 2) {
  525. var source = new RegExp(splits[index], "g");
  526. var dest = splits[index + 1];
  527. includeContent = includeContent.replace(source, dest);
  528. }
  529. }
  530. if (match[4]) {
  531. var indexString = match[5];
  532. if (indexString.indexOf("..") !== -1) {
  533. var indexSplits = indexString.split("..");
  534. var minIndex = parseInt(indexSplits[0]);
  535. var maxIndex = parseInt(indexSplits[1]);
  536. var sourceIncludeContent = includeContent.slice(0);
  537. includeContent = "";
  538. if (isNaN(maxIndex)) {
  539. maxIndex = this._indexParameters[indexSplits[1]];
  540. }
  541. for (var i = minIndex; i < maxIndex; i++) {
  542. if (!this._engine.supportsUniformBuffers) {
  543. // Ubo replacement
  544. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  545. return p1 + "{X}";
  546. });
  547. }
  548. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  549. }
  550. }
  551. else {
  552. if (!this._engine.supportsUniformBuffers) {
  553. // Ubo replacement
  554. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  555. return p1 + "{X}";
  556. });
  557. }
  558. includeContent = includeContent.replace(/\{X\}/g, indexString);
  559. }
  560. }
  561. // Replace
  562. returnValue = returnValue.replace(match[0], includeContent);
  563. }
  564. else {
  565. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  566. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  567. Effect.IncludesShadersStore[includeFile] = fileContent;
  568. _this._processIncludes(returnValue, callback);
  569. });
  570. return;
  571. }
  572. match = regex.exec(sourceCode);
  573. }
  574. callback(returnValue);
  575. };
  576. Effect.prototype._processPrecision = function (source) {
  577. if (source.indexOf("precision highp float") === -1) {
  578. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  579. source = "precision mediump float;\n" + source;
  580. }
  581. else {
  582. source = "precision highp float;\n" + source;
  583. }
  584. }
  585. else {
  586. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  587. source = source.replace("precision highp float", "precision mediump float");
  588. }
  589. }
  590. return source;
  591. };
  592. /**
  593. * Recompiles the webGL program
  594. * @param vertexSourceCode The source code for the vertex shader.
  595. * @param fragmentSourceCode The source code for the fragment shader.
  596. * @param onCompiled Callback called when completed.
  597. * @param onError Callback called on error.
  598. */
  599. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  600. var _this = this;
  601. this._isReady = false;
  602. this._vertexSourceCodeOverride = vertexSourceCode;
  603. this._fragmentSourceCodeOverride = fragmentSourceCode;
  604. this.onError = function (effect, error) {
  605. if (onError) {
  606. onError(error);
  607. }
  608. };
  609. this.onCompiled = function () {
  610. var scenes = _this.getEngine().scenes;
  611. for (var i = 0; i < scenes.length; i++) {
  612. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  613. }
  614. if (onCompiled) {
  615. onCompiled(_this._program);
  616. }
  617. };
  618. this._fallbacks = null;
  619. this._prepareEffect();
  620. };
  621. /**
  622. * Gets the uniform locations of the the specified variable names
  623. * @param names THe names of the variables to lookup.
  624. * @returns Array of locations in the same order as variable names.
  625. */
  626. Effect.prototype.getSpecificUniformLocations = function (names) {
  627. var engine = this._engine;
  628. return engine.getUniforms(this._program, names);
  629. };
  630. /**
  631. * Prepares the effect
  632. */
  633. Effect.prototype._prepareEffect = function () {
  634. var attributesNames = this._attributesNames;
  635. var defines = this.defines;
  636. var fallbacks = this._fallbacks;
  637. this._valueCache = {};
  638. var previousProgram = this._program;
  639. try {
  640. var engine = this._engine;
  641. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  642. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  643. }
  644. else {
  645. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  646. }
  647. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  648. if (engine.supportsUniformBuffers) {
  649. for (var name in this._uniformBuffersNames) {
  650. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  651. }
  652. }
  653. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  654. this._attributes = engine.getAttributes(this._program, attributesNames);
  655. var index;
  656. for (index = 0; index < this._samplers.length; index++) {
  657. var sampler = this.getUniform(this._samplers[index]);
  658. if (sampler == null) {
  659. this._samplers.splice(index, 1);
  660. index--;
  661. }
  662. }
  663. engine.bindSamplers(this);
  664. this._compilationError = "";
  665. this._isReady = true;
  666. if (this.onCompiled) {
  667. this.onCompiled(this);
  668. }
  669. this.onCompileObservable.notifyObservers(this);
  670. this.onCompileObservable.clear();
  671. // Unbind mesh reference in fallbacks
  672. if (this._fallbacks) {
  673. this._fallbacks.unBindMesh();
  674. }
  675. if (previousProgram) {
  676. this.getEngine()._deleteProgram(previousProgram);
  677. }
  678. }
  679. catch (e) {
  680. this._compilationError = e.message;
  681. // Let's go through fallbacks then
  682. BABYLON.Tools.Error("Unable to compile effect:");
  683. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  684. return " " + uniform;
  685. }));
  686. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  687. return " " + attribute;
  688. }));
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * This function will add a new shader to the shader store
  1220. * @param name the name of the shader
  1221. * @param pixelShader optional pixel shader content
  1222. * @param vertexShader optional vertex shader content
  1223. */
  1224. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1225. if (pixelShader) {
  1226. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1227. }
  1228. if (vertexShader) {
  1229. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1230. }
  1231. };
  1232. /**
  1233. * Resets the cache of effects.
  1234. */
  1235. Effect.ResetCache = function () {
  1236. Effect._baseCache = {};
  1237. };
  1238. Effect._uniqueIdSeed = 0;
  1239. Effect._baseCache = {};
  1240. /**
  1241. * Store of each shader (The can be looked up using effect.key)
  1242. */
  1243. Effect.ShadersStore = {};
  1244. /**
  1245. * Store of each included file for a shader (The can be looked up using effect.key)
  1246. */
  1247. Effect.IncludesShadersStore = {};
  1248. return Effect;
  1249. }());
  1250. BABYLON.Effect = Effect;
  1251. })(BABYLON || (BABYLON = {}));
  1252. //# sourceMappingURL=babylon.effect.js.map
  1253. //# sourceMappingURL=babylon.types.js.map
  1254. var BABYLON;
  1255. (function (BABYLON) {
  1256. var KeyboardEventTypes = /** @class */ (function () {
  1257. function KeyboardEventTypes() {
  1258. }
  1259. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1260. get: function () {
  1261. return KeyboardEventTypes._KEYDOWN;
  1262. },
  1263. enumerable: true,
  1264. configurable: true
  1265. });
  1266. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1267. get: function () {
  1268. return KeyboardEventTypes._KEYUP;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. KeyboardEventTypes._KEYDOWN = 0x01;
  1274. KeyboardEventTypes._KEYUP = 0x02;
  1275. return KeyboardEventTypes;
  1276. }());
  1277. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1278. var KeyboardInfo = /** @class */ (function () {
  1279. function KeyboardInfo(type, event) {
  1280. this.type = type;
  1281. this.event = event;
  1282. }
  1283. return KeyboardInfo;
  1284. }());
  1285. BABYLON.KeyboardInfo = KeyboardInfo;
  1286. /**
  1287. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1288. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1289. */
  1290. var KeyboardInfoPre = /** @class */ (function (_super) {
  1291. __extends(KeyboardInfoPre, _super);
  1292. function KeyboardInfoPre(type, event) {
  1293. var _this = _super.call(this, type, event) || this;
  1294. _this.skipOnPointerObservable = false;
  1295. return _this;
  1296. }
  1297. return KeyboardInfoPre;
  1298. }(KeyboardInfo));
  1299. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1300. })(BABYLON || (BABYLON = {}));
  1301. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1302. var BABYLON;
  1303. (function (BABYLON) {
  1304. var PointerEventTypes = /** @class */ (function () {
  1305. function PointerEventTypes() {
  1306. }
  1307. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERDOWN;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERUP;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERMOVE;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERWHEEL;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERPICK;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1343. get: function () {
  1344. return PointerEventTypes._POINTERTAP;
  1345. },
  1346. enumerable: true,
  1347. configurable: true
  1348. });
  1349. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1350. get: function () {
  1351. return PointerEventTypes._POINTERDOUBLETAP;
  1352. },
  1353. enumerable: true,
  1354. configurable: true
  1355. });
  1356. PointerEventTypes._POINTERDOWN = 0x01;
  1357. PointerEventTypes._POINTERUP = 0x02;
  1358. PointerEventTypes._POINTERMOVE = 0x04;
  1359. PointerEventTypes._POINTERWHEEL = 0x08;
  1360. PointerEventTypes._POINTERPICK = 0x10;
  1361. PointerEventTypes._POINTERTAP = 0x20;
  1362. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1363. return PointerEventTypes;
  1364. }());
  1365. BABYLON.PointerEventTypes = PointerEventTypes;
  1366. var PointerInfoBase = /** @class */ (function () {
  1367. function PointerInfoBase(type, event) {
  1368. this.type = type;
  1369. this.event = event;
  1370. }
  1371. return PointerInfoBase;
  1372. }());
  1373. BABYLON.PointerInfoBase = PointerInfoBase;
  1374. /**
  1375. * This class is used to store pointer related info for the onPrePointerObservable event.
  1376. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1377. */
  1378. var PointerInfoPre = /** @class */ (function (_super) {
  1379. __extends(PointerInfoPre, _super);
  1380. function PointerInfoPre(type, event, localX, localY) {
  1381. var _this = _super.call(this, type, event) || this;
  1382. /**
  1383. * Ray from a pointer if availible (eg. 6dof controller)
  1384. */
  1385. _this.ray = null;
  1386. _this.skipOnPointerObservable = false;
  1387. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1388. return _this;
  1389. }
  1390. return PointerInfoPre;
  1391. }(PointerInfoBase));
  1392. BABYLON.PointerInfoPre = PointerInfoPre;
  1393. /**
  1394. * This type contains all the data related to a pointer event in Babylon.js.
  1395. * 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.
  1396. */
  1397. var PointerInfo = /** @class */ (function (_super) {
  1398. __extends(PointerInfo, _super);
  1399. function PointerInfo(type, event, pickInfo) {
  1400. var _this = _super.call(this, type, event) || this;
  1401. _this.pickInfo = pickInfo;
  1402. return _this;
  1403. }
  1404. return PointerInfo;
  1405. }(PointerInfoBase));
  1406. BABYLON.PointerInfo = PointerInfo;
  1407. })(BABYLON || (BABYLON = {}));
  1408. //# sourceMappingURL=babylon.pointerEvents.js.map
  1409. var BABYLON;
  1410. (function (BABYLON) {
  1411. BABYLON.ToGammaSpace = 1 / 2.2;
  1412. BABYLON.ToLinearSpace = 2.2;
  1413. BABYLON.Epsilon = 0.001;
  1414. /**
  1415. * Class used to hold a RBG color
  1416. */
  1417. var Color3 = /** @class */ (function () {
  1418. /**
  1419. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1420. * @param r defines the red component (between 0 and 1, default is 0)
  1421. * @param g defines the green component (between 0 and 1, default is 0)
  1422. * @param b defines the blue component (between 0 and 1, default is 0)
  1423. */
  1424. function Color3(
  1425. /**
  1426. * Defines the red component (between 0 and 1, default is 0)
  1427. */
  1428. r,
  1429. /**
  1430. * Defines the green component (between 0 and 1, default is 0)
  1431. */
  1432. g,
  1433. /**
  1434. * Defines the blue component (between 0 and 1, default is 0)
  1435. */
  1436. b) {
  1437. if (r === void 0) { r = 0; }
  1438. if (g === void 0) { g = 0; }
  1439. if (b === void 0) { b = 0; }
  1440. this.r = r;
  1441. this.g = g;
  1442. this.b = b;
  1443. }
  1444. /**
  1445. * Creates a string with the Color3 current values
  1446. * @returns the string representation of the Color3 object
  1447. */
  1448. Color3.prototype.toString = function () {
  1449. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1450. };
  1451. /**
  1452. * Returns the string "Color3"
  1453. * @returns "Color3"
  1454. */
  1455. Color3.prototype.getClassName = function () {
  1456. return "Color3";
  1457. };
  1458. /**
  1459. * Compute the Color3 hash code
  1460. * @returns an unique number that can be used to hash Color3 objects
  1461. */
  1462. Color3.prototype.getHashCode = function () {
  1463. var hash = this.r || 0;
  1464. hash = (hash * 397) ^ (this.g || 0);
  1465. hash = (hash * 397) ^ (this.b || 0);
  1466. return hash;
  1467. };
  1468. // Operators
  1469. /**
  1470. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1471. * @param array defines the array where to store the r,g,b components
  1472. * @param index defines an optional index in the target array to define where to start storing values
  1473. * @returns the current Color3 object
  1474. */
  1475. Color3.prototype.toArray = function (array, index) {
  1476. if (index === undefined) {
  1477. index = 0;
  1478. }
  1479. array[index] = this.r;
  1480. array[index + 1] = this.g;
  1481. array[index + 2] = this.b;
  1482. return this;
  1483. };
  1484. /**
  1485. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1486. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1487. * @returns a new {BABYLON.Color4} object
  1488. */
  1489. Color3.prototype.toColor4 = function (alpha) {
  1490. if (alpha === void 0) { alpha = 1; }
  1491. return new Color4(this.r, this.g, this.b, alpha);
  1492. };
  1493. /**
  1494. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1495. * @returns the new array
  1496. */
  1497. Color3.prototype.asArray = function () {
  1498. var result = new Array();
  1499. this.toArray(result, 0);
  1500. return result;
  1501. };
  1502. /**
  1503. * Returns the luminance value
  1504. * @returns a float value
  1505. */
  1506. Color3.prototype.toLuminance = function () {
  1507. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1508. };
  1509. /**
  1510. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1511. * @param otherColor defines the second operand
  1512. * @returns the new Color3 object
  1513. */
  1514. Color3.prototype.multiply = function (otherColor) {
  1515. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1516. };
  1517. /**
  1518. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1519. * @param otherColor defines the second operand
  1520. * @param result defines the Color3 object where to store the result
  1521. * @returns the current Color3
  1522. */
  1523. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1524. result.r = this.r * otherColor.r;
  1525. result.g = this.g * otherColor.g;
  1526. result.b = this.b * otherColor.b;
  1527. return this;
  1528. };
  1529. /**
  1530. * Determines equality between Color3 objects
  1531. * @param otherColor defines the second operand
  1532. * @returns true if the rgb values are equal to the given ones
  1533. */
  1534. Color3.prototype.equals = function (otherColor) {
  1535. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1536. };
  1537. /**
  1538. * Determines equality between the current Color3 object and a set of r,b,g values
  1539. * @param r defines the red component to check
  1540. * @param g defines the green component to check
  1541. * @param b defines the blue component to check
  1542. * @returns true if the rgb values are equal to the given ones
  1543. */
  1544. Color3.prototype.equalsFloats = function (r, g, b) {
  1545. return this.r === r && this.g === g && this.b === b;
  1546. };
  1547. /**
  1548. * Multiplies in place each rgb value by scale
  1549. * @param scale defines the scaling factor
  1550. * @returns the updated Color3
  1551. */
  1552. Color3.prototype.scale = function (scale) {
  1553. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1554. };
  1555. /**
  1556. * Multiplies the rgb values by scale and stores the result into "result"
  1557. * @param scale defines the scaling factor
  1558. * @param result defines the Color3 object where to store the result
  1559. * @returns the unmodified current Color3
  1560. */
  1561. Color3.prototype.scaleToRef = function (scale, result) {
  1562. result.r = this.r * scale;
  1563. result.g = this.g * scale;
  1564. result.b = this.b * scale;
  1565. return this;
  1566. };
  1567. /**
  1568. * Scale the current Color3 values by a factor and add the result to a given Color3
  1569. * @param scale defines the scale factor
  1570. * @param result defines color to store the result into
  1571. * @returns the unmodified current Color3
  1572. */
  1573. Color3.prototype.scaleAndAddToRef = 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. * Clamps the rgb values by the min and max values and stores the result into "result"
  1581. * @param min defines minimum clamping value (default is 0)
  1582. * @param max defines maximum clamping value (default is 1)
  1583. * @param result defines color to store the result into
  1584. * @returns the original Color3
  1585. */
  1586. Color3.prototype.clampToRef = function (min, max, result) {
  1587. if (min === void 0) { min = 0; }
  1588. if (max === void 0) { max = 1; }
  1589. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1590. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1591. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1592. return this;
  1593. };
  1594. /**
  1595. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1596. * @param otherColor defines the second operand
  1597. * @returns the new Color3
  1598. */
  1599. Color3.prototype.add = function (otherColor) {
  1600. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1601. };
  1602. /**
  1603. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1604. * @param otherColor defines the second operand
  1605. * @param result defines Color3 object to store the result into
  1606. * @returns the unmodified current Color3
  1607. */
  1608. Color3.prototype.addToRef = function (otherColor, result) {
  1609. result.r = this.r + otherColor.r;
  1610. result.g = this.g + otherColor.g;
  1611. result.b = this.b + otherColor.b;
  1612. return this;
  1613. };
  1614. /**
  1615. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1616. * @param otherColor defines the second operand
  1617. * @returns the new Color3
  1618. */
  1619. Color3.prototype.subtract = function (otherColor) {
  1620. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1621. };
  1622. /**
  1623. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1624. * @param otherColor defines the second operand
  1625. * @param result defines Color3 object to store the result into
  1626. * @returns the unmodified current Color3
  1627. */
  1628. Color3.prototype.subtractToRef = function (otherColor, result) {
  1629. result.r = this.r - otherColor.r;
  1630. result.g = this.g - otherColor.g;
  1631. result.b = this.b - otherColor.b;
  1632. return this;
  1633. };
  1634. /**
  1635. * Copy the current object
  1636. * @returns a new Color3 copied the current one
  1637. */
  1638. Color3.prototype.clone = function () {
  1639. return new Color3(this.r, this.g, this.b);
  1640. };
  1641. /**
  1642. * Copies the rgb values from the source in the current Color3
  1643. * @param source defines the source Color3 object
  1644. * @returns the updated Color3 object
  1645. */
  1646. Color3.prototype.copyFrom = function (source) {
  1647. this.r = source.r;
  1648. this.g = source.g;
  1649. this.b = source.b;
  1650. return this;
  1651. };
  1652. /**
  1653. * Updates the Color3 rgb values from the given floats
  1654. * @param r defines the red component to read from
  1655. * @param g defines the green component to read from
  1656. * @param b defines the blue component to read from
  1657. * @returns the current Color3 object
  1658. */
  1659. Color3.prototype.copyFromFloats = function (r, g, b) {
  1660. this.r = r;
  1661. this.g = g;
  1662. this.b = b;
  1663. return this;
  1664. };
  1665. /**
  1666. * Updates the Color3 rgb values from the given floats
  1667. * @param r defines the red component to read from
  1668. * @param g defines the green component to read from
  1669. * @param b defines the blue component to read from
  1670. * @returns the current Color3 object
  1671. */
  1672. Color3.prototype.set = function (r, g, b) {
  1673. return this.copyFromFloats(r, g, b);
  1674. };
  1675. /**
  1676. * Compute the Color3 hexadecimal code as a string
  1677. * @returns a string containing the hexadecimal representation of the Color3 object
  1678. */
  1679. Color3.prototype.toHexString = function () {
  1680. var intR = (this.r * 255) | 0;
  1681. var intG = (this.g * 255) | 0;
  1682. var intB = (this.b * 255) | 0;
  1683. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1684. };
  1685. /**
  1686. * Computes a new Color3 converted from the current one to linear space
  1687. * @returns a new Color3 object
  1688. */
  1689. Color3.prototype.toLinearSpace = function () {
  1690. var convertedColor = new Color3();
  1691. this.toLinearSpaceToRef(convertedColor);
  1692. return convertedColor;
  1693. };
  1694. /**
  1695. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1696. * @param convertedColor defines the Color3 object where to store the linear space version
  1697. * @returns the unmodified Color3
  1698. */
  1699. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1700. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1701. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1702. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1703. return this;
  1704. };
  1705. /**
  1706. * Computes a new Color3 converted from the current one to gamma space
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.prototype.toGammaSpace = function () {
  1710. var convertedColor = new Color3();
  1711. this.toGammaSpaceToRef(convertedColor);
  1712. return convertedColor;
  1713. };
  1714. /**
  1715. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1716. * @param convertedColor defines the Color3 object where to store the gamma space version
  1717. * @returns the unmodified Color3
  1718. */
  1719. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1720. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1721. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1722. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1723. return this;
  1724. };
  1725. // Statics
  1726. /**
  1727. * Creates a new Color3 from the string containing valid hexadecimal values
  1728. * @param hex defines a string containing valid hexadecimal values
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.FromHexString = function (hex) {
  1732. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1733. return new Color3(0, 0, 0);
  1734. }
  1735. var r = parseInt(hex.substring(1, 3), 16);
  1736. var g = parseInt(hex.substring(3, 5), 16);
  1737. var b = parseInt(hex.substring(5, 7), 16);
  1738. return Color3.FromInts(r, g, b);
  1739. };
  1740. /**
  1741. * Creates a new Vector3 from the starting index of the given array
  1742. * @param array defines the source array
  1743. * @param offset defines an offset in the source array
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.FromArray = function (array, offset) {
  1747. if (offset === void 0) { offset = 0; }
  1748. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1749. };
  1750. /**
  1751. * Creates a new Color3 from integer values (< 256)
  1752. * @param r defines the red component to read from (value between 0 and 255)
  1753. * @param g defines the green component to read from (value between 0 and 255)
  1754. * @param b defines the blue component to read from (value between 0 and 255)
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.FromInts = function (r, g, b) {
  1758. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1759. };
  1760. /**
  1761. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1762. * @param start defines the start Color3 value
  1763. * @param end defines the end Color3 value
  1764. * @param amount defines the gradient value between start and end
  1765. * @returns a new Color3 object
  1766. */
  1767. Color3.Lerp = function (start, end, amount) {
  1768. var r = start.r + ((end.r - start.r) * amount);
  1769. var g = start.g + ((end.g - start.g) * amount);
  1770. var b = start.b + ((end.b - start.b) * amount);
  1771. return new Color3(r, g, b);
  1772. };
  1773. /**
  1774. * Returns a Color3 value containing a red color
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.Red = function () { return new Color3(1, 0, 0); };
  1778. /**
  1779. * Returns a Color3 value containing a green color
  1780. * @returns a new Color3 object
  1781. */
  1782. Color3.Green = function () { return new Color3(0, 1, 0); };
  1783. /**
  1784. * Returns a Color3 value containing a blue color
  1785. * @returns a new Color3 object
  1786. */
  1787. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1788. /**
  1789. * Returns a Color3 value containing a black color
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.Black = function () { return new Color3(0, 0, 0); };
  1793. /**
  1794. * Returns a Color3 value containing a white color
  1795. * @returns a new Color3 object
  1796. */
  1797. Color3.White = function () { return new Color3(1, 1, 1); };
  1798. /**
  1799. * Returns a Color3 value containing a purple color
  1800. * @returns a new Color3 object
  1801. */
  1802. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1803. /**
  1804. * Returns a Color3 value containing a magenta color
  1805. * @returns a new Color3 object
  1806. */
  1807. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1808. /**
  1809. * Returns a Color3 value containing a yellow color
  1810. * @returns a new Color3 object
  1811. */
  1812. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1813. /**
  1814. * Returns a Color3 value containing a gray color
  1815. * @returns a new Color3 object
  1816. */
  1817. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1818. /**
  1819. * Returns a Color3 value containing a teal color
  1820. * @returns a new Color3 object
  1821. */
  1822. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1823. /**
  1824. * Returns a Color3 value containing a random color
  1825. * @returns a new Color3 object
  1826. */
  1827. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1828. return Color3;
  1829. }());
  1830. BABYLON.Color3 = Color3;
  1831. /**
  1832. * Class used to hold a RBGA color
  1833. */
  1834. var Color4 = /** @class */ (function () {
  1835. /**
  1836. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1837. * @param r defines the red component (between 0 and 1, default is 0)
  1838. * @param g defines the green component (between 0 and 1, default is 0)
  1839. * @param b defines the blue component (between 0 and 1, default is 0)
  1840. * @param a defines the alpha component (between 0 and 1, default is 1)
  1841. */
  1842. function Color4(
  1843. /**
  1844. * Defines the red component (between 0 and 1, default is 0)
  1845. */
  1846. r,
  1847. /**
  1848. * Defines the green component (between 0 and 1, default is 0)
  1849. */
  1850. g,
  1851. /**
  1852. * Defines the blue component (between 0 and 1, default is 0)
  1853. */
  1854. b,
  1855. /**
  1856. * Defines the alpha component (between 0 and 1, default is 1)
  1857. */
  1858. a) {
  1859. if (r === void 0) { r = 0; }
  1860. if (g === void 0) { g = 0; }
  1861. if (b === void 0) { b = 0; }
  1862. if (a === void 0) { a = 1; }
  1863. this.r = r;
  1864. this.g = g;
  1865. this.b = b;
  1866. this.a = a;
  1867. }
  1868. // Operators
  1869. /**
  1870. * Adds in place the given Color4 values to the current Color4 object
  1871. * @param right defines the second operand
  1872. * @returns the current updated Color4 object
  1873. */
  1874. Color4.prototype.addInPlace = function (right) {
  1875. this.r += right.r;
  1876. this.g += right.g;
  1877. this.b += right.b;
  1878. this.a += right.a;
  1879. return this;
  1880. };
  1881. /**
  1882. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1883. * @returns the new array
  1884. */
  1885. Color4.prototype.asArray = function () {
  1886. var result = new Array();
  1887. this.toArray(result, 0);
  1888. return result;
  1889. };
  1890. /**
  1891. * Stores from the starting index in the given array the Color4 successive values
  1892. * @param array defines the array where to store the r,g,b components
  1893. * @param index defines an optional index in the target array to define where to start storing values
  1894. * @returns the current Color4 object
  1895. */
  1896. Color4.prototype.toArray = function (array, index) {
  1897. if (index === undefined) {
  1898. index = 0;
  1899. }
  1900. array[index] = this.r;
  1901. array[index + 1] = this.g;
  1902. array[index + 2] = this.b;
  1903. array[index + 3] = this.a;
  1904. return this;
  1905. };
  1906. /**
  1907. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1908. * @param right defines the second operand
  1909. * @returns a new Color4 object
  1910. */
  1911. Color4.prototype.add = function (right) {
  1912. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1913. };
  1914. /**
  1915. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1916. * @param right defines the second operand
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.subtract = function (right) {
  1920. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1921. };
  1922. /**
  1923. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1924. * @param right defines the second operand
  1925. * @param result defines the Color4 object where to store the result
  1926. * @returns the current Color4 object
  1927. */
  1928. Color4.prototype.subtractToRef = function (right, result) {
  1929. result.r = this.r - right.r;
  1930. result.g = this.g - right.g;
  1931. result.b = this.b - right.b;
  1932. result.a = this.a - right.a;
  1933. return this;
  1934. };
  1935. /**
  1936. * Creates a new Color4 with the current Color4 values multiplied by scale
  1937. * @param scale defines the scaling factor to apply
  1938. * @returns a new Color4 object
  1939. */
  1940. Color4.prototype.scale = function (scale) {
  1941. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1942. };
  1943. /**
  1944. * Multiplies the current Color4 values by scale and stores the result in "result"
  1945. * @param scale defines the scaling factor to apply
  1946. * @param result defines the Color4 object where to store the result
  1947. * @returns the current unmodified Color4
  1948. */
  1949. Color4.prototype.scaleToRef = function (scale, result) {
  1950. result.r = this.r * scale;
  1951. result.g = this.g * scale;
  1952. result.b = this.b * scale;
  1953. result.a = this.a * scale;
  1954. return this;
  1955. };
  1956. /**
  1957. * Scale the current Color4 values by a factor and add the result to a given Color4
  1958. * @param scale defines the scale factor
  1959. * @param result defines the Color4 object where to store the result
  1960. * @returns the unmodified current Color4
  1961. */
  1962. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1963. result.r += this.r * scale;
  1964. result.g += this.g * scale;
  1965. result.b += this.b * scale;
  1966. result.a += this.a * scale;
  1967. return this;
  1968. };
  1969. /**
  1970. * Clamps the rgb values by the min and max values and stores the result into "result"
  1971. * @param min defines minimum clamping value (default is 0)
  1972. * @param max defines maximum clamping value (default is 1)
  1973. * @param result defines color to store the result into.
  1974. * @returns the cuurent Color4
  1975. */
  1976. Color4.prototype.clampToRef = function (min, max, result) {
  1977. if (min === void 0) { min = 0; }
  1978. if (max === void 0) { max = 1; }
  1979. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1980. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1981. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1982. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1983. return this;
  1984. };
  1985. /**
  1986. * Multipy an Color4 value by another and return a new Color4 object
  1987. * @param color defines the Color4 value to multiply by
  1988. * @returns a new Color4 object
  1989. */
  1990. Color4.prototype.multiply = function (color) {
  1991. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1992. };
  1993. /**
  1994. * Multipy a Color4 value by another and push the result in a reference value
  1995. * @param color defines the Color4 value to multiply by
  1996. * @param result defines the Color4 to fill the result in
  1997. * @returns the result Color4
  1998. */
  1999. Color4.prototype.multiplyToRef = function (color, result) {
  2000. result.r = this.r * color.r;
  2001. result.g = this.g * color.g;
  2002. result.b = this.b * color.b;
  2003. result.a = this.a * color.a;
  2004. return result;
  2005. };
  2006. /**
  2007. * Creates a string with the Color4 current values
  2008. * @returns the string representation of the Color4 object
  2009. */
  2010. Color4.prototype.toString = function () {
  2011. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2012. };
  2013. /**
  2014. * Returns the string "Color4"
  2015. * @returns "Color4"
  2016. */
  2017. Color4.prototype.getClassName = function () {
  2018. return "Color4";
  2019. };
  2020. /**
  2021. * Compute the Color4 hash code
  2022. * @returns an unique number that can be used to hash Color4 objects
  2023. */
  2024. Color4.prototype.getHashCode = function () {
  2025. var hash = this.r || 0;
  2026. hash = (hash * 397) ^ (this.g || 0);
  2027. hash = (hash * 397) ^ (this.b || 0);
  2028. hash = (hash * 397) ^ (this.a || 0);
  2029. return hash;
  2030. };
  2031. /**
  2032. * Creates a new Color4 copied from the current one
  2033. * @returns a new Color4 object
  2034. */
  2035. Color4.prototype.clone = function () {
  2036. return new Color4(this.r, this.g, this.b, this.a);
  2037. };
  2038. /**
  2039. * Copies the given Color4 values into the current one
  2040. * @param source defines the source Color4 object
  2041. * @returns the current updated Color4 object
  2042. */
  2043. Color4.prototype.copyFrom = function (source) {
  2044. this.r = source.r;
  2045. this.g = source.g;
  2046. this.b = source.b;
  2047. this.a = source.a;
  2048. return this;
  2049. };
  2050. /**
  2051. * Copies the given float values into the current one
  2052. * @param r defines the red component to read from
  2053. * @param g defines the green component to read from
  2054. * @param b defines the blue component to read from
  2055. * @param a defines the alpha component to read from
  2056. * @returns the current updated Color4 object
  2057. */
  2058. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2059. this.r = r;
  2060. this.g = g;
  2061. this.b = b;
  2062. this.a = a;
  2063. return this;
  2064. };
  2065. /**
  2066. * Copies the given float values into the current one
  2067. * @param r defines the red component to read from
  2068. * @param g defines the green component to read from
  2069. * @param b defines the blue component to read from
  2070. * @param a defines the alpha component to read from
  2071. * @returns the current updated Color4 object
  2072. */
  2073. Color4.prototype.set = function (r, g, b, a) {
  2074. return this.copyFromFloats(r, g, b, a);
  2075. };
  2076. /**
  2077. * Compute the Color4 hexadecimal code as a string
  2078. * @returns a string containing the hexadecimal representation of the Color4 object
  2079. */
  2080. Color4.prototype.toHexString = function () {
  2081. var intR = (this.r * 255) | 0;
  2082. var intG = (this.g * 255) | 0;
  2083. var intB = (this.b * 255) | 0;
  2084. var intA = (this.a * 255) | 0;
  2085. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2086. };
  2087. /**
  2088. * Computes a new Color4 converted from the current one to linear space
  2089. * @returns a new Color4 object
  2090. */
  2091. Color4.prototype.toLinearSpace = function () {
  2092. var convertedColor = new Color4();
  2093. this.toLinearSpaceToRef(convertedColor);
  2094. return convertedColor;
  2095. };
  2096. /**
  2097. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2098. * @param convertedColor defines the Color4 object where to store the linear space version
  2099. * @returns the unmodified Color4
  2100. */
  2101. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2102. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2103. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2104. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2105. convertedColor.a = this.a;
  2106. return this;
  2107. };
  2108. /**
  2109. * Computes a new Color4 converted from the current one to gamma space
  2110. * @returns a new Color4 object
  2111. */
  2112. Color4.prototype.toGammaSpace = function () {
  2113. var convertedColor = new Color4();
  2114. this.toGammaSpaceToRef(convertedColor);
  2115. return convertedColor;
  2116. };
  2117. /**
  2118. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2119. * @param convertedColor defines the Color4 object where to store the gamma space version
  2120. * @returns the unmodified Color4
  2121. */
  2122. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2123. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2124. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2125. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2126. convertedColor.a = this.a;
  2127. return this;
  2128. };
  2129. // Statics
  2130. /**
  2131. * Creates a new Color4 from the string containing valid hexadecimal values
  2132. * @param hex defines a string containing valid hexadecimal values
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromHexString = function (hex) {
  2136. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2137. return new Color4(0.0, 0.0, 0.0, 0.0);
  2138. }
  2139. var r = parseInt(hex.substring(1, 3), 16);
  2140. var g = parseInt(hex.substring(3, 5), 16);
  2141. var b = parseInt(hex.substring(5, 7), 16);
  2142. var a = parseInt(hex.substring(7, 9), 16);
  2143. return Color4.FromInts(r, g, b, a);
  2144. };
  2145. /**
  2146. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2147. * @param left defines the start value
  2148. * @param right defines the end value
  2149. * @param amount defines the gradient factor
  2150. * @returns a new Color4 object
  2151. */
  2152. Color4.Lerp = function (left, right, amount) {
  2153. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2154. Color4.LerpToRef(left, right, amount, result);
  2155. return result;
  2156. };
  2157. /**
  2158. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2159. * @param left defines the start value
  2160. * @param right defines the end value
  2161. * @param amount defines the gradient factor
  2162. * @param result defines the Color4 object where to store data
  2163. */
  2164. Color4.LerpToRef = function (left, right, amount, result) {
  2165. result.r = left.r + (right.r - left.r) * amount;
  2166. result.g = left.g + (right.g - left.g) * amount;
  2167. result.b = left.b + (right.b - left.b) * amount;
  2168. result.a = left.a + (right.a - left.a) * amount;
  2169. };
  2170. /**
  2171. * Creates a new Color4 from the starting index element of the given array
  2172. * @param array defines the source array to read from
  2173. * @param offset defines the offset in the source array
  2174. * @returns a new Color4 object
  2175. */
  2176. Color4.FromArray = function (array, offset) {
  2177. if (offset === void 0) { offset = 0; }
  2178. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2179. };
  2180. /**
  2181. * Creates a new Color3 from integer values (< 256)
  2182. * @param r defines the red component to read from (value between 0 and 255)
  2183. * @param g defines the green component to read from (value between 0 and 255)
  2184. * @param b defines the blue component to read from (value between 0 and 255)
  2185. * @param a defines the alpha component to read from (value between 0 and 255)
  2186. * @returns a new Color3 object
  2187. */
  2188. Color4.FromInts = function (r, g, b, a) {
  2189. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2190. };
  2191. /**
  2192. * Check the content of a given array and convert it to an array containing RGBA data
  2193. * If the original array was already containing count * 4 values then it is returned directly
  2194. * @param colors defines the array to check
  2195. * @param count defines the number of RGBA data to expect
  2196. * @returns an array containing count * 4 values (RGBA)
  2197. */
  2198. Color4.CheckColors4 = function (colors, count) {
  2199. // Check if color3 was used
  2200. if (colors.length === count * 3) {
  2201. var colors4 = [];
  2202. for (var index = 0; index < colors.length; index += 3) {
  2203. var newIndex = (index / 3) * 4;
  2204. colors4[newIndex] = colors[index];
  2205. colors4[newIndex + 1] = colors[index + 1];
  2206. colors4[newIndex + 2] = colors[index + 2];
  2207. colors4[newIndex + 3] = 1.0;
  2208. }
  2209. return colors4;
  2210. }
  2211. return colors;
  2212. };
  2213. return Color4;
  2214. }());
  2215. BABYLON.Color4 = Color4;
  2216. /**
  2217. * Class representing a vector containing 2 coordinates
  2218. */
  2219. var Vector2 = /** @class */ (function () {
  2220. /**
  2221. * Creates a new Vector2 from the given x and y coordinates
  2222. * @param x defines the first coordinate
  2223. * @param y defines the second coordinate
  2224. */
  2225. function Vector2(
  2226. /** defines the first coordinate */
  2227. x,
  2228. /** defines the second coordinate */
  2229. y) {
  2230. if (x === void 0) { x = 0; }
  2231. if (y === void 0) { y = 0; }
  2232. this.x = x;
  2233. this.y = y;
  2234. }
  2235. /**
  2236. * Gets a string with the Vector2 coordinates
  2237. * @returns a string with the Vector2 coordinates
  2238. */
  2239. Vector2.prototype.toString = function () {
  2240. return "{X: " + this.x + " Y:" + this.y + "}";
  2241. };
  2242. /**
  2243. * Gets class name
  2244. * @returns the string "Vector2"
  2245. */
  2246. Vector2.prototype.getClassName = function () {
  2247. return "Vector2";
  2248. };
  2249. /**
  2250. * Gets current vector hash code
  2251. * @returns the Vector2 hash code as a number
  2252. */
  2253. Vector2.prototype.getHashCode = function () {
  2254. var hash = this.x || 0;
  2255. hash = (hash * 397) ^ (this.y || 0);
  2256. return hash;
  2257. };
  2258. // Operators
  2259. /**
  2260. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2261. * @param array defines the source array
  2262. * @param index defines the offset in source array
  2263. * @returns the current Vector2
  2264. */
  2265. Vector2.prototype.toArray = function (array, index) {
  2266. if (index === void 0) { index = 0; }
  2267. array[index] = this.x;
  2268. array[index + 1] = this.y;
  2269. return this;
  2270. };
  2271. /**
  2272. * Copy the current vector to an array
  2273. * @returns a new array with 2 elements: the Vector2 coordinates.
  2274. */
  2275. Vector2.prototype.asArray = function () {
  2276. var result = new Array();
  2277. this.toArray(result, 0);
  2278. return result;
  2279. };
  2280. /**
  2281. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2282. * @param source defines the source Vector2
  2283. * @returns the current updated Vector2
  2284. */
  2285. Vector2.prototype.copyFrom = function (source) {
  2286. this.x = source.x;
  2287. this.y = source.y;
  2288. return this;
  2289. };
  2290. /**
  2291. * Sets the Vector2 coordinates with the given floats
  2292. * @param x defines the first coordinate
  2293. * @param y defines the second coordinate
  2294. * @returns the current updated Vector2
  2295. */
  2296. Vector2.prototype.copyFromFloats = function (x, y) {
  2297. this.x = x;
  2298. this.y = y;
  2299. return this;
  2300. };
  2301. /**
  2302. * Sets the Vector2 coordinates with the given floats
  2303. * @param x defines the first coordinate
  2304. * @param y defines the second coordinate
  2305. * @returns the current updated Vector2
  2306. */
  2307. Vector2.prototype.set = function (x, y) {
  2308. return this.copyFromFloats(x, y);
  2309. };
  2310. /**
  2311. * Add another vector with the current one
  2312. * @param otherVector defines the other vector
  2313. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2314. */
  2315. Vector2.prototype.add = function (otherVector) {
  2316. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2317. };
  2318. /**
  2319. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2320. * @param otherVector defines the other vector
  2321. * @param result defines the target vector
  2322. * @returns the unmodified current Vector2
  2323. */
  2324. Vector2.prototype.addToRef = function (otherVector, result) {
  2325. result.x = this.x + otherVector.x;
  2326. result.y = this.y + otherVector.y;
  2327. return this;
  2328. };
  2329. /**
  2330. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2331. * @param otherVector defines the other vector
  2332. * @returns the current updated Vector2
  2333. */
  2334. Vector2.prototype.addInPlace = function (otherVector) {
  2335. this.x += otherVector.x;
  2336. this.y += otherVector.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2341. * @param otherVector defines the other vector
  2342. * @returns a new Vector2
  2343. */
  2344. Vector2.prototype.addVector3 = function (otherVector) {
  2345. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2346. };
  2347. /**
  2348. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2349. * @param otherVector defines the other vector
  2350. * @returns a new Vector2
  2351. */
  2352. Vector2.prototype.subtract = function (otherVector) {
  2353. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2354. };
  2355. /**
  2356. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2357. * @param otherVector defines the other vector
  2358. * @param result defines the target vector
  2359. * @returns the unmodified current Vector2
  2360. */
  2361. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2362. result.x = this.x - otherVector.x;
  2363. result.y = this.y - otherVector.y;
  2364. return this;
  2365. };
  2366. /**
  2367. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2368. * @param otherVector defines the other vector
  2369. * @returns the current updated Vector2
  2370. */
  2371. Vector2.prototype.subtractInPlace = function (otherVector) {
  2372. this.x -= otherVector.x;
  2373. this.y -= otherVector.y;
  2374. return this;
  2375. };
  2376. /**
  2377. * Multiplies in place the current Vector2 coordinates by the given ones
  2378. * @param otherVector defines the other vector
  2379. * @returns the current updated Vector2
  2380. */
  2381. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2382. this.x *= otherVector.x;
  2383. this.y *= otherVector.y;
  2384. return this;
  2385. };
  2386. /**
  2387. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2388. * @param otherVector defines the other vector
  2389. * @returns a new Vector2
  2390. */
  2391. Vector2.prototype.multiply = function (otherVector) {
  2392. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2393. };
  2394. /**
  2395. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2396. * @param otherVector defines the other vector
  2397. * @param result defines the target vector
  2398. * @returns the unmodified current Vector2
  2399. */
  2400. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2401. result.x = this.x * otherVector.x;
  2402. result.y = this.y * otherVector.y;
  2403. return this;
  2404. };
  2405. /**
  2406. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2407. * @param x defines the first coordinate
  2408. * @param y defines the second coordinate
  2409. * @returns a new Vector2
  2410. */
  2411. Vector2.prototype.multiplyByFloats = function (x, y) {
  2412. return new Vector2(this.x * x, this.y * y);
  2413. };
  2414. /**
  2415. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2416. * @param otherVector defines the other vector
  2417. * @returns a new Vector2
  2418. */
  2419. Vector2.prototype.divide = function (otherVector) {
  2420. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2421. };
  2422. /**
  2423. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2424. * @param otherVector defines the other vector
  2425. * @param result defines the target vector
  2426. * @returns the unmodified current Vector2
  2427. */
  2428. Vector2.prototype.divideToRef = function (otherVector, result) {
  2429. result.x = this.x / otherVector.x;
  2430. result.y = this.y / otherVector.y;
  2431. return this;
  2432. };
  2433. /**
  2434. * Divides the current Vector2 coordinates by the given ones
  2435. * @param otherVector defines the other vector
  2436. * @returns the current updated Vector2
  2437. */
  2438. Vector2.prototype.divideInPlace = function (otherVector) {
  2439. return this.divideToRef(otherVector, this);
  2440. };
  2441. /**
  2442. * Gets a new Vector2 with current Vector2 negated coordinates
  2443. * @returns a new Vector2
  2444. */
  2445. Vector2.prototype.negate = function () {
  2446. return new Vector2(-this.x, -this.y);
  2447. };
  2448. /**
  2449. * Multiply the Vector2 coordinates by scale
  2450. * @param scale defines the scaling factor
  2451. * @returns the current updated Vector2
  2452. */
  2453. Vector2.prototype.scaleInPlace = function (scale) {
  2454. this.x *= scale;
  2455. this.y *= scale;
  2456. return this;
  2457. };
  2458. /**
  2459. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2460. * @param scale defines the scaling factor
  2461. * @returns a new Vector2
  2462. */
  2463. Vector2.prototype.scale = function (scale) {
  2464. var result = new Vector2(0, 0);
  2465. this.scaleToRef(scale, result);
  2466. return result;
  2467. };
  2468. /**
  2469. * Scale the current Vector2 values by a factor to a given Vector2
  2470. * @param scale defines the scale factor
  2471. * @param result defines the Vector2 object where to store the result
  2472. * @returns the unmodified current Vector2
  2473. */
  2474. Vector2.prototype.scaleToRef = function (scale, result) {
  2475. result.x = this.x * scale;
  2476. result.y = this.y * scale;
  2477. return this;
  2478. };
  2479. /**
  2480. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2481. * @param scale defines the scale factor
  2482. * @param result defines the Vector2 object where to store the result
  2483. * @returns the unmodified current Vector2
  2484. */
  2485. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2486. result.x += this.x * scale;
  2487. result.y += this.y * scale;
  2488. return this;
  2489. };
  2490. /**
  2491. * Gets a boolean if two vectors are equals
  2492. * @param otherVector defines the other vector
  2493. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2494. */
  2495. Vector2.prototype.equals = function (otherVector) {
  2496. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2497. };
  2498. /**
  2499. * Gets a boolean if two vectors are equals (using an epsilon value)
  2500. * @param otherVector defines the other vector
  2501. * @param epsilon defines the minimal distance to consider equality
  2502. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2503. */
  2504. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2505. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2506. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2507. };
  2508. /**
  2509. * Gets a new Vector2 from current Vector2 floored values
  2510. * @returns a new Vector2
  2511. */
  2512. Vector2.prototype.floor = function () {
  2513. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2514. };
  2515. /**
  2516. * Gets a new Vector2 from current Vector2 floored values
  2517. * @returns a new Vector2
  2518. */
  2519. Vector2.prototype.fract = function () {
  2520. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2521. };
  2522. // Properties
  2523. /**
  2524. * Gets the length of the vector
  2525. * @returns the vector length (float)
  2526. */
  2527. Vector2.prototype.length = function () {
  2528. return Math.sqrt(this.x * this.x + this.y * this.y);
  2529. };
  2530. /**
  2531. * Gets the vector squared length
  2532. * @returns the vector squared length (float)
  2533. */
  2534. Vector2.prototype.lengthSquared = function () {
  2535. return (this.x * this.x + this.y * this.y);
  2536. };
  2537. // Methods
  2538. /**
  2539. * Normalize the vector
  2540. * @returns the current updated Vector2
  2541. */
  2542. Vector2.prototype.normalize = function () {
  2543. var len = this.length();
  2544. if (len === 0)
  2545. return this;
  2546. var num = 1.0 / len;
  2547. this.x *= num;
  2548. this.y *= num;
  2549. return this;
  2550. };
  2551. /**
  2552. * Gets a new Vector2 copied from the Vector2
  2553. * @returns a new Vector2
  2554. */
  2555. Vector2.prototype.clone = function () {
  2556. return new Vector2(this.x, this.y);
  2557. };
  2558. // Statics
  2559. /**
  2560. * Gets a new Vector2(0, 0)
  2561. * @returns a new Vector2
  2562. */
  2563. Vector2.Zero = function () {
  2564. return new Vector2(0, 0);
  2565. };
  2566. /**
  2567. * Gets a new Vector2(1, 1)
  2568. * @returns a new Vector2
  2569. */
  2570. Vector2.One = function () {
  2571. return new Vector2(1, 1);
  2572. };
  2573. /**
  2574. * Gets a new Vector2 set from the given index element of the given array
  2575. * @param array defines the data source
  2576. * @param offset defines the offset in the data source
  2577. * @returns a new Vector2
  2578. */
  2579. Vector2.FromArray = function (array, offset) {
  2580. if (offset === void 0) { offset = 0; }
  2581. return new Vector2(array[offset], array[offset + 1]);
  2582. };
  2583. /**
  2584. * Sets "result" from the given index element of the given array
  2585. * @param array defines the data source
  2586. * @param offset defines the offset in the data source
  2587. * @param result defines the target vector
  2588. */
  2589. Vector2.FromArrayToRef = function (array, offset, result) {
  2590. result.x = array[offset];
  2591. result.y = array[offset + 1];
  2592. };
  2593. /**
  2594. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2595. * @param value1 defines 1st point of control
  2596. * @param value2 defines 2nd point of control
  2597. * @param value3 defines 3rd point of control
  2598. * @param value4 defines 4th point of control
  2599. * @param amount defines the interpolation factor
  2600. * @returns a new Vector2
  2601. */
  2602. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2603. var squared = amount * amount;
  2604. var cubed = amount * squared;
  2605. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2606. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2607. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2608. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2609. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2610. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2611. return new Vector2(x, y);
  2612. };
  2613. /**
  2614. * 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".
  2615. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2616. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2617. * @param value defines the value to clamp
  2618. * @param min defines the lower limit
  2619. * @param max defines the upper limit
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Clamp = function (value, min, max) {
  2623. var x = value.x;
  2624. x = (x > max.x) ? max.x : x;
  2625. x = (x < min.x) ? min.x : x;
  2626. var y = value.y;
  2627. y = (y > max.y) ? max.y : y;
  2628. y = (y < min.y) ? min.y : y;
  2629. return new Vector2(x, y);
  2630. };
  2631. /**
  2632. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2633. * @param value1 defines the 1st control point
  2634. * @param tangent1 defines the outgoing tangent
  2635. * @param value2 defines the 2nd control point
  2636. * @param tangent2 defines the incoming tangent
  2637. * @param amount defines the interpolation factor
  2638. * @returns a new Vector2
  2639. */
  2640. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2641. var squared = amount * amount;
  2642. var cubed = amount * squared;
  2643. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2644. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2645. var part3 = (cubed - (2.0 * squared)) + amount;
  2646. var part4 = cubed - squared;
  2647. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2648. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2649. return new Vector2(x, y);
  2650. };
  2651. /**
  2652. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2653. * @param start defines the start vector
  2654. * @param end defines the end vector
  2655. * @param amount defines the interpolation factor
  2656. * @returns a new Vector2
  2657. */
  2658. Vector2.Lerp = function (start, end, amount) {
  2659. var x = start.x + ((end.x - start.x) * amount);
  2660. var y = start.y + ((end.y - start.y) * amount);
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Gets the dot product of the vector "left" and the vector "right"
  2665. * @param left defines first vector
  2666. * @param right defines second vector
  2667. * @returns the dot product (float)
  2668. */
  2669. Vector2.Dot = function (left, right) {
  2670. return left.x * right.x + left.y * right.y;
  2671. };
  2672. /**
  2673. * Returns a new Vector2 equal to the normalized given vector
  2674. * @param vector defines the vector to normalize
  2675. * @returns a new Vector2
  2676. */
  2677. Vector2.Normalize = function (vector) {
  2678. var newVector = vector.clone();
  2679. newVector.normalize();
  2680. return newVector;
  2681. };
  2682. /**
  2683. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2684. * @param left defines 1st vector
  2685. * @param right defines 2nd vector
  2686. * @returns a new Vector2
  2687. */
  2688. Vector2.Minimize = function (left, right) {
  2689. var x = (left.x < right.x) ? left.x : right.x;
  2690. var y = (left.y < right.y) ? left.y : right.y;
  2691. return new Vector2(x, y);
  2692. };
  2693. /**
  2694. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2695. * @param left defines 1st vector
  2696. * @param right defines 2nd vector
  2697. * @returns a new Vector2
  2698. */
  2699. Vector2.Maximize = function (left, right) {
  2700. var x = (left.x > right.x) ? left.x : right.x;
  2701. var y = (left.y > right.y) ? left.y : right.y;
  2702. return new Vector2(x, y);
  2703. };
  2704. /**
  2705. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2706. * @param vector defines the vector to transform
  2707. * @param transformation defines the matrix to apply
  2708. * @returns a new Vector2
  2709. */
  2710. Vector2.Transform = function (vector, transformation) {
  2711. var r = Vector2.Zero();
  2712. Vector2.TransformToRef(vector, transformation, r);
  2713. return r;
  2714. };
  2715. /**
  2716. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2717. * @param vector defines the vector to transform
  2718. * @param transformation defines the matrix to apply
  2719. * @param result defines the target vector
  2720. */
  2721. Vector2.TransformToRef = function (vector, transformation, result) {
  2722. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2723. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2724. result.x = x;
  2725. result.y = y;
  2726. };
  2727. /**
  2728. * Determines if a given vector is included in a triangle
  2729. * @param p defines the vector to test
  2730. * @param p0 defines 1st triangle point
  2731. * @param p1 defines 2nd triangle point
  2732. * @param p2 defines 3rd triangle point
  2733. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2734. */
  2735. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2736. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2737. var sign = a < 0 ? -1 : 1;
  2738. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2739. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2740. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2741. };
  2742. /**
  2743. * Gets the distance between the vectors "value1" and "value2"
  2744. * @param value1 defines first vector
  2745. * @param value2 defines second vector
  2746. * @returns the distance between vectors
  2747. */
  2748. Vector2.Distance = function (value1, value2) {
  2749. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2750. };
  2751. /**
  2752. * Returns the squared distance between the vectors "value1" and "value2"
  2753. * @param value1 defines first vector
  2754. * @param value2 defines second vector
  2755. * @returns the squared distance between vectors
  2756. */
  2757. Vector2.DistanceSquared = function (value1, value2) {
  2758. var x = value1.x - value2.x;
  2759. var y = value1.y - value2.y;
  2760. return (x * x) + (y * y);
  2761. };
  2762. /**
  2763. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2764. * @param value1 defines first vector
  2765. * @param value2 defines second vector
  2766. * @returns a new Vector2
  2767. */
  2768. Vector2.Center = function (value1, value2) {
  2769. var center = value1.add(value2);
  2770. center.scaleInPlace(0.5);
  2771. return center;
  2772. };
  2773. /**
  2774. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2775. * @param p defines the middle point
  2776. * @param segA defines one point of the segment
  2777. * @param segB defines the other point of the segment
  2778. * @returns the shortest distance
  2779. */
  2780. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2781. var l2 = Vector2.DistanceSquared(segA, segB);
  2782. if (l2 === 0.0) {
  2783. return Vector2.Distance(p, segA);
  2784. }
  2785. var v = segB.subtract(segA);
  2786. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2787. var proj = segA.add(v.multiplyByFloats(t, t));
  2788. return Vector2.Distance(p, proj);
  2789. };
  2790. return Vector2;
  2791. }());
  2792. BABYLON.Vector2 = Vector2;
  2793. /**
  2794. * Classed used to store (x,y,z) vector representation
  2795. * A Vector3 is the main object used in 3D geometry
  2796. * It can represent etiher the coordinates of a point the space, either a direction
  2797. * Reminder: Babylon.js uses a left handed forward facing system
  2798. */
  2799. var Vector3 = /** @class */ (function () {
  2800. /**
  2801. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2802. * @param x defines the first coordinates (on X axis)
  2803. * @param y defines the second coordinates (on Y axis)
  2804. * @param z defines the third coordinates (on Z axis)
  2805. */
  2806. function Vector3(
  2807. /**
  2808. * Defines the first coordinates (on X axis)
  2809. */
  2810. x,
  2811. /**
  2812. * Defines the second coordinates (on Y axis)
  2813. */
  2814. y,
  2815. /**
  2816. * Defines the third coordinates (on Z axis)
  2817. */
  2818. z) {
  2819. if (x === void 0) { x = 0; }
  2820. if (y === void 0) { y = 0; }
  2821. if (z === void 0) { z = 0; }
  2822. this.x = x;
  2823. this.y = y;
  2824. this.z = z;
  2825. }
  2826. /**
  2827. * Creates a string representation of the Vector3
  2828. * @returns a string with the Vector3 coordinates.
  2829. */
  2830. Vector3.prototype.toString = function () {
  2831. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2832. };
  2833. /**
  2834. * Gets the class name
  2835. * @returns the string "Vector3"
  2836. */
  2837. Vector3.prototype.getClassName = function () {
  2838. return "Vector3";
  2839. };
  2840. /**
  2841. * Creates the Vector3 hash code
  2842. * @returns a number which tends to be unique between Vector3 instances
  2843. */
  2844. Vector3.prototype.getHashCode = function () {
  2845. var hash = this.x || 0;
  2846. hash = (hash * 397) ^ (this.y || 0);
  2847. hash = (hash * 397) ^ (this.z || 0);
  2848. return hash;
  2849. };
  2850. // Operators
  2851. /**
  2852. * Creates an array containing three elements : the coordinates of the Vector3
  2853. * @returns a new array of numbers
  2854. */
  2855. Vector3.prototype.asArray = function () {
  2856. var result = [];
  2857. this.toArray(result, 0);
  2858. return result;
  2859. };
  2860. /**
  2861. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2862. * @param array defines the destination array
  2863. * @param index defines the offset in the destination array
  2864. * @returns the current Vector3
  2865. */
  2866. Vector3.prototype.toArray = function (array, index) {
  2867. if (index === void 0) { index = 0; }
  2868. array[index] = this.x;
  2869. array[index + 1] = this.y;
  2870. array[index + 2] = this.z;
  2871. return this;
  2872. };
  2873. /**
  2874. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2875. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2876. */
  2877. Vector3.prototype.toQuaternion = function () {
  2878. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2879. };
  2880. /**
  2881. * Adds the given vector to the current Vector3
  2882. * @param otherVector defines the second operand
  2883. * @returns the current updated Vector3
  2884. */
  2885. Vector3.prototype.addInPlace = function (otherVector) {
  2886. this.x += otherVector.x;
  2887. this.y += otherVector.y;
  2888. this.z += otherVector.z;
  2889. return this;
  2890. };
  2891. /**
  2892. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2893. * @param otherVector defines the second operand
  2894. * @returns the resulting Vector3
  2895. */
  2896. Vector3.prototype.add = function (otherVector) {
  2897. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2898. };
  2899. /**
  2900. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2901. * @param otherVector defines the second operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.addToRef = function (otherVector, result) {
  2906. result.x = this.x + otherVector.x;
  2907. result.y = this.y + otherVector.y;
  2908. result.z = this.z + otherVector.z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Subtract the given vector from the current Vector3
  2913. * @param otherVector defines the second operand
  2914. * @returns the current updated Vector3
  2915. */
  2916. Vector3.prototype.subtractInPlace = function (otherVector) {
  2917. this.x -= otherVector.x;
  2918. this.y -= otherVector.y;
  2919. this.z -= otherVector.z;
  2920. return this;
  2921. };
  2922. /**
  2923. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2924. * @param otherVector defines the second operand
  2925. * @returns the resulting Vector3
  2926. */
  2927. Vector3.prototype.subtract = function (otherVector) {
  2928. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2929. };
  2930. /**
  2931. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2932. * @param otherVector defines the second operand
  2933. * @param result defines the Vector3 object where to store the result
  2934. * @returns the current Vector3
  2935. */
  2936. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2937. result.x = this.x - otherVector.x;
  2938. result.y = this.y - otherVector.y;
  2939. result.z = this.z - otherVector.z;
  2940. return this;
  2941. };
  2942. /**
  2943. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2944. * @param x defines the x coordinate of the operand
  2945. * @param y defines the y coordinate of the operand
  2946. * @param z defines the z coordinate of the operand
  2947. * @returns the resulting Vector3
  2948. */
  2949. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2950. return new Vector3(this.x - x, this.y - y, this.z - z);
  2951. };
  2952. /**
  2953. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2954. * @param x defines the x coordinate of the operand
  2955. * @param y defines the y coordinate of the operand
  2956. * @param z defines the z coordinate of the operand
  2957. * @param result defines the Vector3 object where to store the result
  2958. * @returns the current Vector3
  2959. */
  2960. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2961. result.x = this.x - x;
  2962. result.y = this.y - y;
  2963. result.z = this.z - z;
  2964. return this;
  2965. };
  2966. /**
  2967. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2968. * @returns a new Vector3
  2969. */
  2970. Vector3.prototype.negate = function () {
  2971. return new Vector3(-this.x, -this.y, -this.z);
  2972. };
  2973. /**
  2974. * Multiplies the Vector3 coordinates by the float "scale"
  2975. * @param scale defines the multiplier factor
  2976. * @returns the current updated Vector3
  2977. */
  2978. Vector3.prototype.scaleInPlace = function (scale) {
  2979. this.x *= scale;
  2980. this.y *= scale;
  2981. this.z *= scale;
  2982. return this;
  2983. };
  2984. /**
  2985. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2986. * @param scale defines the multiplier factor
  2987. * @returns a new Vector3
  2988. */
  2989. Vector3.prototype.scale = function (scale) {
  2990. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2991. };
  2992. /**
  2993. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2994. * @param scale defines the multiplier factor
  2995. * @param result defines the Vector3 object where to store the result
  2996. * @returns the current Vector3
  2997. */
  2998. Vector3.prototype.scaleToRef = function (scale, result) {
  2999. result.x = this.x * scale;
  3000. result.y = this.y * scale;
  3001. result.z = this.z * scale;
  3002. return this;
  3003. };
  3004. /**
  3005. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3006. * @param scale defines the scale factor
  3007. * @param result defines the Vector3 object where to store the result
  3008. * @returns the unmodified current Vector3
  3009. */
  3010. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3011. result.x += this.x * scale;
  3012. result.y += this.y * scale;
  3013. result.z += this.z * scale;
  3014. return this;
  3015. };
  3016. /**
  3017. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3018. * @param otherVector defines the second operand
  3019. * @returns true if both vectors are equals
  3020. */
  3021. Vector3.prototype.equals = function (otherVector) {
  3022. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3023. };
  3024. /**
  3025. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3026. * @param otherVector defines the second operand
  3027. * @param epsilon defines the minimal distance to define values as equals
  3028. * @returns true if both vectors are distant less than epsilon
  3029. */
  3030. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3031. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3032. 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);
  3033. };
  3034. /**
  3035. * Returns true if the current Vector3 coordinates equals the given floats
  3036. * @param x defines the x coordinate of the operand
  3037. * @param y defines the y coordinate of the operand
  3038. * @param z defines the z coordinate of the operand
  3039. * @returns true if both vectors are equals
  3040. */
  3041. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3042. return this.x === x && this.y === y && this.z === z;
  3043. };
  3044. /**
  3045. * Multiplies the current Vector3 coordinates by the given ones
  3046. * @param otherVector defines the second operand
  3047. * @returns the current updated Vector3
  3048. */
  3049. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3050. this.x *= otherVector.x;
  3051. this.y *= otherVector.y;
  3052. this.z *= otherVector.z;
  3053. return this;
  3054. };
  3055. /**
  3056. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3057. * @param otherVector defines the second operand
  3058. * @returns the new Vector3
  3059. */
  3060. Vector3.prototype.multiply = function (otherVector) {
  3061. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3062. };
  3063. /**
  3064. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3065. * @param otherVector defines the second operand
  3066. * @param result defines the Vector3 object where to store the result
  3067. * @returns the current Vector3
  3068. */
  3069. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3070. result.x = this.x * otherVector.x;
  3071. result.y = this.y * otherVector.y;
  3072. result.z = this.z * otherVector.z;
  3073. return this;
  3074. };
  3075. /**
  3076. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3077. * @param x defines the x coordinate of the operand
  3078. * @param y defines the y coordinate of the operand
  3079. * @param z defines the z coordinate of the operand
  3080. * @returns the new Vector3
  3081. */
  3082. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3083. return new Vector3(this.x * x, this.y * y, this.z * z);
  3084. };
  3085. /**
  3086. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3087. * @param otherVector defines the second operand
  3088. * @returns the new Vector3
  3089. */
  3090. Vector3.prototype.divide = function (otherVector) {
  3091. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3092. };
  3093. /**
  3094. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3095. * @param otherVector defines the second operand
  3096. * @param result defines the Vector3 object where to store the result
  3097. * @returns the current Vector3
  3098. */
  3099. Vector3.prototype.divideToRef = function (otherVector, result) {
  3100. result.x = this.x / otherVector.x;
  3101. result.y = this.y / otherVector.y;
  3102. result.z = this.z / otherVector.z;
  3103. return this;
  3104. };
  3105. /**
  3106. * Divides the current Vector3 coordinates by the given ones.
  3107. * @param otherVector defines the second operand
  3108. * @returns the current updated Vector3
  3109. */
  3110. Vector3.prototype.divideInPlace = function (otherVector) {
  3111. return this.divideToRef(otherVector, this);
  3112. };
  3113. /**
  3114. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3115. * @param other defines the second operand
  3116. * @returns the current updated Vector3
  3117. */
  3118. Vector3.prototype.minimizeInPlace = function (other) {
  3119. if (other.x < this.x)
  3120. this.x = other.x;
  3121. if (other.y < this.y)
  3122. this.y = other.y;
  3123. if (other.z < this.z)
  3124. this.z = other.z;
  3125. return this;
  3126. };
  3127. /**
  3128. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3129. * @param other defines the second operand
  3130. * @returns the current updated Vector3
  3131. */
  3132. Vector3.prototype.maximizeInPlace = function (other) {
  3133. if (other.x > this.x)
  3134. this.x = other.x;
  3135. if (other.y > this.y)
  3136. this.y = other.y;
  3137. if (other.z > this.z)
  3138. this.z = other.z;
  3139. return this;
  3140. };
  3141. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3142. /**
  3143. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3144. */
  3145. get: function () {
  3146. var absX = Math.abs(this.x);
  3147. var absY = Math.abs(this.y);
  3148. if (absX !== absY) {
  3149. return true;
  3150. }
  3151. var absZ = Math.abs(this.z);
  3152. if (absX !== absZ) {
  3153. return true;
  3154. }
  3155. if (absY !== absZ) {
  3156. return true;
  3157. }
  3158. return false;
  3159. },
  3160. enumerable: true,
  3161. configurable: true
  3162. });
  3163. /**
  3164. * Gets a new Vector3 from current Vector3 floored values
  3165. * @returns a new Vector3
  3166. */
  3167. Vector3.prototype.floor = function () {
  3168. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3169. };
  3170. /**
  3171. * Gets a new Vector3 from current Vector3 floored values
  3172. * @returns a new Vector3
  3173. */
  3174. Vector3.prototype.fract = function () {
  3175. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3176. };
  3177. // Properties
  3178. /**
  3179. * Gets the length of the Vector3
  3180. * @returns the length of the Vecto3
  3181. */
  3182. Vector3.prototype.length = function () {
  3183. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3184. };
  3185. /**
  3186. * Gets the squared length of the Vector3
  3187. * @returns squared length of the Vector3
  3188. */
  3189. Vector3.prototype.lengthSquared = function () {
  3190. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3191. };
  3192. /**
  3193. * Normalize the current Vector3.
  3194. * Please note that this is an in place operation.
  3195. * @returns the current updated Vector3
  3196. */
  3197. Vector3.prototype.normalize = function () {
  3198. var len = this.length();
  3199. if (len === 0 || len === 1.0)
  3200. return this;
  3201. var num = 1.0 / len;
  3202. this.x *= num;
  3203. this.y *= num;
  3204. this.z *= num;
  3205. return this;
  3206. };
  3207. /**
  3208. * Normalize the current Vector3 to a new vector
  3209. * @returns the new Vector3
  3210. */
  3211. Vector3.prototype.normalizeToNew = function () {
  3212. var normalized = new Vector3(0, 0, 0);
  3213. this.normalizeToRef(normalized);
  3214. return normalized;
  3215. };
  3216. /**
  3217. * Normalize the current Vector3 to the reference
  3218. * @param reference define the Vector3 to update
  3219. * @returns the updated Vector3
  3220. */
  3221. Vector3.prototype.normalizeToRef = function (reference) {
  3222. var len = this.length();
  3223. if (len === 0 || len === 1.0) {
  3224. reference.set(this.x, this.y, this.z);
  3225. return reference;
  3226. }
  3227. var scale = 1.0 / len;
  3228. this.scaleToRef(scale, reference);
  3229. return reference;
  3230. };
  3231. /**
  3232. * Creates a new Vector3 copied from the current Vector3
  3233. * @returns the new Vector3
  3234. */
  3235. Vector3.prototype.clone = function () {
  3236. return new Vector3(this.x, this.y, this.z);
  3237. };
  3238. /**
  3239. * Copies the given vector coordinates to the current Vector3 ones
  3240. * @param source defines the source Vector3
  3241. * @returns the current updated Vector3
  3242. */
  3243. Vector3.prototype.copyFrom = function (source) {
  3244. this.x = source.x;
  3245. this.y = source.y;
  3246. this.z = source.z;
  3247. return this;
  3248. };
  3249. /**
  3250. * Copies the given floats to the current Vector3 coordinates
  3251. * @param x defines the x coordinate of the operand
  3252. * @param y defines the y coordinate of the operand
  3253. * @param z defines the z coordinate of the operand
  3254. * @returns the current updated Vector3
  3255. */
  3256. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3257. this.x = x;
  3258. this.y = y;
  3259. this.z = z;
  3260. return this;
  3261. };
  3262. /**
  3263. * Copies the given floats to the current Vector3 coordinates
  3264. * @param x defines the x coordinate of the operand
  3265. * @param y defines the y coordinate of the operand
  3266. * @param z defines the z coordinate of the operand
  3267. * @returns the current updated Vector3
  3268. */
  3269. Vector3.prototype.set = function (x, y, z) {
  3270. return this.copyFromFloats(x, y, z);
  3271. };
  3272. // Statics
  3273. /**
  3274. * Get the clip factor between two vectors
  3275. * @param vector0 defines the first operand
  3276. * @param vector1 defines the second operand
  3277. * @param axis defines the axis to use
  3278. * @param size defines the size along the axis
  3279. * @returns the clip factor
  3280. */
  3281. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3282. var d0 = Vector3.Dot(vector0, axis) - size;
  3283. var d1 = Vector3.Dot(vector1, axis) - size;
  3284. var s = d0 / (d0 - d1);
  3285. return s;
  3286. };
  3287. /**
  3288. * Get angle between two vectors
  3289. * @param vector0 angle between vector0 and vector1
  3290. * @param vector1 angle between vector0 and vector1
  3291. * @param normal direction of the normal
  3292. * @return the angle between vector0 and vector1
  3293. */
  3294. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3295. var v0 = vector0.clone().normalize();
  3296. var v1 = vector1.clone().normalize();
  3297. var dot = Vector3.Dot(v0, v1);
  3298. var n = Vector3.Cross(v0, v1);
  3299. if (Vector3.Dot(n, normal) > 0) {
  3300. return Math.acos(dot);
  3301. }
  3302. return -Math.acos(dot);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set from the index "offset" of the given array
  3306. * @param array defines the source array
  3307. * @param offset defines the offset in the source array
  3308. * @returns the new Vector3
  3309. */
  3310. Vector3.FromArray = function (array, offset) {
  3311. if (!offset) {
  3312. offset = 0;
  3313. }
  3314. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3318. * This function is deprecated. Use FromArray instead
  3319. * @param array defines the source array
  3320. * @param offset defines the offset in the source array
  3321. * @returns the new Vector3
  3322. */
  3323. Vector3.FromFloatArray = function (array, offset) {
  3324. return Vector3.FromArray(array, offset);
  3325. };
  3326. /**
  3327. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3328. * @param array defines the source array
  3329. * @param offset defines the offset in the source array
  3330. * @param result defines the Vector3 where to store the result
  3331. */
  3332. Vector3.FromArrayToRef = function (array, offset, result) {
  3333. result.x = array[offset];
  3334. result.y = array[offset + 1];
  3335. result.z = array[offset + 2];
  3336. };
  3337. /**
  3338. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3339. * This function is deprecated. Use FromArrayToRef instead.
  3340. * @param array defines the source array
  3341. * @param offset defines the offset in the source array
  3342. * @param result defines the Vector3 where to store the result
  3343. */
  3344. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3345. return Vector3.FromArrayToRef(array, offset, result);
  3346. };
  3347. /**
  3348. * Sets the given vector "result" with the given floats.
  3349. * @param x defines the x coordinate of the source
  3350. * @param y defines the y coordinate of the source
  3351. * @param z defines the z coordinate of the source
  3352. * @param result defines the Vector3 where to store the result
  3353. */
  3354. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3355. result.x = x;
  3356. result.y = y;
  3357. result.z = z;
  3358. };
  3359. /**
  3360. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3361. * @returns a new empty Vector3
  3362. */
  3363. Vector3.Zero = function () {
  3364. return new Vector3(0.0, 0.0, 0.0);
  3365. };
  3366. /**
  3367. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3368. * @returns a new unit Vector3
  3369. */
  3370. Vector3.One = function () {
  3371. return new Vector3(1.0, 1.0, 1.0);
  3372. };
  3373. /**
  3374. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3375. * @returns a new up Vector3
  3376. */
  3377. Vector3.Up = function () {
  3378. return new Vector3(0.0, 1.0, 0.0);
  3379. };
  3380. /**
  3381. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3382. * @returns a new down Vector3
  3383. */
  3384. Vector3.Down = function () {
  3385. return new Vector3(0.0, -1.0, 0.0);
  3386. };
  3387. /**
  3388. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3389. * @returns a new forward Vector3
  3390. */
  3391. Vector3.Forward = function () {
  3392. return new Vector3(0.0, 0.0, 1.0);
  3393. };
  3394. /**
  3395. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3396. * @returns a new right Vector3
  3397. */
  3398. Vector3.Right = function () {
  3399. return new Vector3(1.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3403. * @returns a new left Vector3
  3404. */
  3405. Vector3.Left = function () {
  3406. return new Vector3(-1.0, 0.0, 0.0);
  3407. };
  3408. /**
  3409. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3410. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3411. * @param vector defines the Vector3 to transform
  3412. * @param transformation defines the transformation matrix
  3413. * @returns the transformed Vector3
  3414. */
  3415. Vector3.TransformCoordinates = function (vector, transformation) {
  3416. var result = Vector3.Zero();
  3417. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3418. return result;
  3419. };
  3420. /**
  3421. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3422. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3423. * @param vector defines the Vector3 to transform
  3424. * @param transformation defines the transformation matrix
  3425. * @param result defines the Vector3 where to store the result
  3426. */
  3427. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3428. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3429. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3430. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3431. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3432. result.x = x / w;
  3433. result.y = y / w;
  3434. result.z = z / w;
  3435. };
  3436. /**
  3437. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3438. * This method computes tranformed coordinates only, not transformed direction vectors
  3439. * @param x define the x coordinate of the source vector
  3440. * @param y define the y coordinate of the source vector
  3441. * @param z define the z coordinate of the source vector
  3442. * @param transformation defines the transformation matrix
  3443. * @param result defines the Vector3 where to store the result
  3444. */
  3445. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3446. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3447. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3448. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3449. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3450. result.x = rx / rw;
  3451. result.y = ry / rw;
  3452. result.z = rz / rw;
  3453. };
  3454. /**
  3455. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3456. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3457. * @param vector defines the Vector3 to transform
  3458. * @param transformation defines the transformation matrix
  3459. * @returns the new Vector3
  3460. */
  3461. Vector3.TransformNormal = function (vector, transformation) {
  3462. var result = Vector3.Zero();
  3463. Vector3.TransformNormalToRef(vector, transformation, result);
  3464. return result;
  3465. };
  3466. /**
  3467. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3468. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3469. * @param vector defines the Vector3 to transform
  3470. * @param transformation defines the transformation matrix
  3471. * @param result defines the Vector3 where to store the result
  3472. */
  3473. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3474. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3475. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3476. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3477. result.x = x;
  3478. result.y = y;
  3479. result.z = z;
  3480. };
  3481. /**
  3482. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3483. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3484. * @param x define the x coordinate of the source vector
  3485. * @param y define the y coordinate of the source vector
  3486. * @param z define the z coordinate of the source vector
  3487. * @param transformation defines the transformation matrix
  3488. * @param result defines the Vector3 where to store the result
  3489. */
  3490. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3491. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3492. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3493. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3494. };
  3495. /**
  3496. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3497. * @param value1 defines the first control point
  3498. * @param value2 defines the second control point
  3499. * @param value3 defines the third control point
  3500. * @param value4 defines the fourth control point
  3501. * @param amount defines the amount on the spline to use
  3502. * @returns the new Vector3
  3503. */
  3504. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3505. var squared = amount * amount;
  3506. var cubed = amount * squared;
  3507. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3508. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3509. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3510. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3511. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3512. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3513. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3514. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3515. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3516. return new Vector3(x, y, z);
  3517. };
  3518. /**
  3519. * 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"
  3520. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3521. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3522. * @param value defines the current value
  3523. * @param min defines the lower range value
  3524. * @param max defines the upper range value
  3525. * @returns the new Vector3
  3526. */
  3527. Vector3.Clamp = function (value, min, max) {
  3528. var x = value.x;
  3529. x = (x > max.x) ? max.x : x;
  3530. x = (x < min.x) ? min.x : x;
  3531. var y = value.y;
  3532. y = (y > max.y) ? max.y : y;
  3533. y = (y < min.y) ? min.y : y;
  3534. var z = value.z;
  3535. z = (z > max.z) ? max.z : z;
  3536. z = (z < min.z) ? min.z : z;
  3537. return new Vector3(x, y, z);
  3538. };
  3539. /**
  3540. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3541. * @param value1 defines the first control point
  3542. * @param tangent1 defines the first tangent vector
  3543. * @param value2 defines the second control point
  3544. * @param tangent2 defines the second tangent vector
  3545. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3549. var squared = amount * amount;
  3550. var cubed = amount * squared;
  3551. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3552. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3553. var part3 = (cubed - (2.0 * squared)) + amount;
  3554. var part4 = cubed - squared;
  3555. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3556. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3557. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3558. return new Vector3(x, y, z);
  3559. };
  3560. /**
  3561. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3562. * @param start defines the start value
  3563. * @param end defines the end value
  3564. * @param amount max defines amount between both (between 0 and 1)
  3565. * @returns the new Vector3
  3566. */
  3567. Vector3.Lerp = function (start, end, amount) {
  3568. var result = new Vector3(0, 0, 0);
  3569. Vector3.LerpToRef(start, end, amount, result);
  3570. return result;
  3571. };
  3572. /**
  3573. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3574. * @param start defines the start value
  3575. * @param end defines the end value
  3576. * @param amount max defines amount between both (between 0 and 1)
  3577. * @param result defines the Vector3 where to store the result
  3578. */
  3579. Vector3.LerpToRef = function (start, end, amount, result) {
  3580. result.x = start.x + ((end.x - start.x) * amount);
  3581. result.y = start.y + ((end.y - start.y) * amount);
  3582. result.z = start.z + ((end.z - start.z) * amount);
  3583. };
  3584. /**
  3585. * Returns the dot product (float) between the vectors "left" and "right"
  3586. * @param left defines the left operand
  3587. * @param right defines the right operand
  3588. * @returns the dot product
  3589. */
  3590. Vector3.Dot = function (left, right) {
  3591. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3592. };
  3593. /**
  3594. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3595. * The cross product is then orthogonal to both "left" and "right"
  3596. * @param left defines the left operand
  3597. * @param right defines the right operand
  3598. * @returns the cross product
  3599. */
  3600. Vector3.Cross = function (left, right) {
  3601. var result = Vector3.Zero();
  3602. Vector3.CrossToRef(left, right, result);
  3603. return result;
  3604. };
  3605. /**
  3606. * Sets the given vector "result" with the cross product of "left" and "right"
  3607. * The cross product is then orthogonal to both "left" and "right"
  3608. * @param left defines the left operand
  3609. * @param right defines the right operand
  3610. * @param result defines the Vector3 where to store the result
  3611. */
  3612. Vector3.CrossToRef = function (left, right, result) {
  3613. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3614. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3615. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3616. result.copyFrom(MathTmp.Vector3[0]);
  3617. };
  3618. /**
  3619. * Returns a new Vector3 as the normalization of the given vector
  3620. * @param vector defines the Vector3 to normalize
  3621. * @returns the new Vector3
  3622. */
  3623. Vector3.Normalize = function (vector) {
  3624. var result = Vector3.Zero();
  3625. Vector3.NormalizeToRef(vector, result);
  3626. return result;
  3627. };
  3628. /**
  3629. * Sets the given vector "result" with the normalization of the given first vector
  3630. * @param vector defines the Vector3 to normalize
  3631. * @param result defines the Vector3 where to store the result
  3632. */
  3633. Vector3.NormalizeToRef = function (vector, result) {
  3634. result.copyFrom(vector);
  3635. result.normalize();
  3636. };
  3637. /**
  3638. * Project a Vector3 onto screen space
  3639. * @param vector defines the Vector3 to project
  3640. * @param world defines the world matrix to use
  3641. * @param transform defines the transform (view x projection) matrix to use
  3642. * @param viewport defines the screen viewport to use
  3643. * @returns the new Vector3
  3644. */
  3645. Vector3.Project = function (vector, world, transform, viewport) {
  3646. var cw = viewport.width;
  3647. var ch = viewport.height;
  3648. var cx = viewport.x;
  3649. var cy = viewport.y;
  3650. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3651. 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);
  3652. var matrix = MathTmp.Matrix[0];
  3653. world.multiplyToRef(transform, matrix);
  3654. matrix.multiplyToRef(viewportMatrix, matrix);
  3655. return Vector3.TransformCoordinates(vector, matrix);
  3656. };
  3657. /**
  3658. * Unproject from screen space to object space
  3659. * @param source defines the screen space Vector3 to use
  3660. * @param viewportWidth defines the current width of the viewport
  3661. * @param viewportHeight defines the current height of the viewport
  3662. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3663. * @param transform defines the transform (view x projection) matrix to use
  3664. * @returns the new Vector3
  3665. */
  3666. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3667. var matrix = MathTmp.Matrix[0];
  3668. world.multiplyToRef(transform, matrix);
  3669. matrix.invert();
  3670. source.x = source.x / viewportWidth * 2 - 1;
  3671. source.y = -(source.y / viewportHeight * 2 - 1);
  3672. var vector = Vector3.TransformCoordinates(source, matrix);
  3673. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3674. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3675. vector = vector.scale(1.0 / num);
  3676. }
  3677. return vector;
  3678. };
  3679. /**
  3680. * Unproject from screen space to object space
  3681. * @param source defines the screen space Vector3 to use
  3682. * @param viewportWidth defines the current width of the viewport
  3683. * @param viewportHeight defines the current height of the viewport
  3684. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3685. * @param view defines the view matrix to use
  3686. * @param projection defines the projection matrix to use
  3687. * @returns the new Vector3
  3688. */
  3689. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3690. var result = Vector3.Zero();
  3691. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3692. return result;
  3693. };
  3694. /**
  3695. * Unproject from screen space to object space
  3696. * @param source defines the screen space Vector3 to use
  3697. * @param viewportWidth defines the current width of the viewport
  3698. * @param viewportHeight defines the current height of the viewport
  3699. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3700. * @param view defines the view matrix to use
  3701. * @param projection defines the projection matrix to use
  3702. * @param result defines the Vector3 where to store the result
  3703. */
  3704. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3705. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3706. };
  3707. /**
  3708. * Unproject from screen space to object space
  3709. * @param sourceX defines the screen space x coordinate to use
  3710. * @param sourceY defines the screen space y coordinate to use
  3711. * @param sourceZ defines the screen space z coordinate to use
  3712. * @param viewportWidth defines the current width of the viewport
  3713. * @param viewportHeight defines the current height of the viewport
  3714. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3715. * @param view defines the view matrix to use
  3716. * @param projection defines the projection matrix to use
  3717. * @param result defines the Vector3 where to store the result
  3718. */
  3719. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3720. var matrix = MathTmp.Matrix[0];
  3721. world.multiplyToRef(view, matrix);
  3722. matrix.multiplyToRef(projection, matrix);
  3723. matrix.invert();
  3724. var screenSource = MathTmp.Vector3[0];
  3725. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3726. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3727. screenSource.z = 2 * sourceZ - 1.0;
  3728. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3729. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3730. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3731. result.scaleInPlace(1.0 / num);
  3732. }
  3733. };
  3734. /**
  3735. * Gets the minimal coordinate values between two Vector3
  3736. * @param left defines the first operand
  3737. * @param right defines the second operand
  3738. * @returns the new Vector3
  3739. */
  3740. Vector3.Minimize = function (left, right) {
  3741. var min = left.clone();
  3742. min.minimizeInPlace(right);
  3743. return min;
  3744. };
  3745. /**
  3746. * Gets the maximal coordinate values between two Vector3
  3747. * @param left defines the first operand
  3748. * @param right defines the second operand
  3749. * @returns the new Vector3
  3750. */
  3751. Vector3.Maximize = function (left, right) {
  3752. var max = left.clone();
  3753. max.maximizeInPlace(right);
  3754. return max;
  3755. };
  3756. /**
  3757. * Returns the distance between the vectors "value1" and "value2"
  3758. * @param value1 defines the first operand
  3759. * @param value2 defines the second operand
  3760. * @returns the distance
  3761. */
  3762. Vector3.Distance = function (value1, value2) {
  3763. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3764. };
  3765. /**
  3766. * Returns the squared distance between the vectors "value1" and "value2"
  3767. * @param value1 defines the first operand
  3768. * @param value2 defines the second operand
  3769. * @returns the squared distance
  3770. */
  3771. Vector3.DistanceSquared = function (value1, value2) {
  3772. var x = value1.x - value2.x;
  3773. var y = value1.y - value2.y;
  3774. var z = value1.z - value2.z;
  3775. return (x * x) + (y * y) + (z * z);
  3776. };
  3777. /**
  3778. * Returns a new Vector3 located at the center between "value1" and "value2"
  3779. * @param value1 defines the first operand
  3780. * @param value2 defines the second operand
  3781. * @returns the new Vector3
  3782. */
  3783. Vector3.Center = function (value1, value2) {
  3784. var center = value1.add(value2);
  3785. center.scaleInPlace(0.5);
  3786. return center;
  3787. };
  3788. /**
  3789. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3790. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3791. * to something in order to rotate it from its local system to the given target system
  3792. * Note: axis1, axis2 and axis3 are normalized during this operation
  3793. * @param axis1 defines the first axis
  3794. * @param axis2 defines the second axis
  3795. * @param axis3 defines the third axis
  3796. * @returns a new Vector3
  3797. */
  3798. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3799. var rotation = Vector3.Zero();
  3800. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3801. return rotation;
  3802. };
  3803. /**
  3804. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3805. * @param axis1 defines the first axis
  3806. * @param axis2 defines the second axis
  3807. * @param axis3 defines the third axis
  3808. * @param ref defines the Vector3 where to store the result
  3809. */
  3810. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3811. var quat = MathTmp.Quaternion[0];
  3812. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3813. quat.toEulerAnglesToRef(ref);
  3814. };
  3815. return Vector3;
  3816. }());
  3817. BABYLON.Vector3 = Vector3;
  3818. //Vector4 class created for EulerAngle class conversion to Quaternion
  3819. var Vector4 = /** @class */ (function () {
  3820. /**
  3821. * Creates a Vector4 object from the given floats.
  3822. */
  3823. function Vector4(x, y, z, w) {
  3824. this.x = x;
  3825. this.y = y;
  3826. this.z = z;
  3827. this.w = w;
  3828. }
  3829. /**
  3830. * Returns the string with the Vector4 coordinates.
  3831. */
  3832. Vector4.prototype.toString = function () {
  3833. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3834. };
  3835. /**
  3836. * Returns the string "Vector4".
  3837. */
  3838. Vector4.prototype.getClassName = function () {
  3839. return "Vector4";
  3840. };
  3841. /**
  3842. * Returns the Vector4 hash code.
  3843. */
  3844. Vector4.prototype.getHashCode = function () {
  3845. var hash = this.x || 0;
  3846. hash = (hash * 397) ^ (this.y || 0);
  3847. hash = (hash * 397) ^ (this.z || 0);
  3848. hash = (hash * 397) ^ (this.w || 0);
  3849. return hash;
  3850. };
  3851. // Operators
  3852. /**
  3853. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3854. */
  3855. Vector4.prototype.asArray = function () {
  3856. var result = new Array();
  3857. this.toArray(result, 0);
  3858. return result;
  3859. };
  3860. /**
  3861. * Populates the given array from the given index with the Vector4 coordinates.
  3862. * Returns the Vector4.
  3863. */
  3864. Vector4.prototype.toArray = function (array, index) {
  3865. if (index === undefined) {
  3866. index = 0;
  3867. }
  3868. array[index] = this.x;
  3869. array[index + 1] = this.y;
  3870. array[index + 2] = this.z;
  3871. array[index + 3] = this.w;
  3872. return this;
  3873. };
  3874. /**
  3875. * Adds the given vector to the current Vector4.
  3876. * Returns the updated Vector4.
  3877. */
  3878. Vector4.prototype.addInPlace = function (otherVector) {
  3879. this.x += otherVector.x;
  3880. this.y += otherVector.y;
  3881. this.z += otherVector.z;
  3882. this.w += otherVector.w;
  3883. return this;
  3884. };
  3885. /**
  3886. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3887. */
  3888. Vector4.prototype.add = function (otherVector) {
  3889. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3890. };
  3891. /**
  3892. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3893. * Returns the current Vector4.
  3894. */
  3895. Vector4.prototype.addToRef = function (otherVector, result) {
  3896. result.x = this.x + otherVector.x;
  3897. result.y = this.y + otherVector.y;
  3898. result.z = this.z + otherVector.z;
  3899. result.w = this.w + otherVector.w;
  3900. return this;
  3901. };
  3902. /**
  3903. * Subtract in place the given vector from the current Vector4.
  3904. * Returns the updated Vector4.
  3905. */
  3906. Vector4.prototype.subtractInPlace = function (otherVector) {
  3907. this.x -= otherVector.x;
  3908. this.y -= otherVector.y;
  3909. this.z -= otherVector.z;
  3910. this.w -= otherVector.w;
  3911. return this;
  3912. };
  3913. /**
  3914. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3915. */
  3916. Vector4.prototype.subtract = function (otherVector) {
  3917. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3918. };
  3919. /**
  3920. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3921. * Returns the current Vector4.
  3922. */
  3923. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3924. result.x = this.x - otherVector.x;
  3925. result.y = this.y - otherVector.y;
  3926. result.z = this.z - otherVector.z;
  3927. result.w = this.w - otherVector.w;
  3928. return this;
  3929. };
  3930. /**
  3931. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3932. */
  3933. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3934. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3935. };
  3936. /**
  3937. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3938. * Returns the current Vector4.
  3939. */
  3940. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3941. result.x = this.x - x;
  3942. result.y = this.y - y;
  3943. result.z = this.z - z;
  3944. result.w = this.w - w;
  3945. return this;
  3946. };
  3947. /**
  3948. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3949. */
  3950. Vector4.prototype.negate = function () {
  3951. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3952. };
  3953. /**
  3954. * Multiplies the current Vector4 coordinates by scale (float).
  3955. * Returns the updated Vector4.
  3956. */
  3957. Vector4.prototype.scaleInPlace = function (scale) {
  3958. this.x *= scale;
  3959. this.y *= scale;
  3960. this.z *= scale;
  3961. this.w *= scale;
  3962. return this;
  3963. };
  3964. /**
  3965. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3966. */
  3967. Vector4.prototype.scale = function (scale) {
  3968. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3969. };
  3970. /**
  3971. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3972. * Returns the current Vector4.
  3973. */
  3974. Vector4.prototype.scaleToRef = function (scale, result) {
  3975. result.x = this.x * scale;
  3976. result.y = this.y * scale;
  3977. result.z = this.z * scale;
  3978. result.w = this.w * scale;
  3979. return this;
  3980. };
  3981. /**
  3982. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3983. * @param scale defines the scale factor
  3984. * @param result defines the Vector4 object where to store the result
  3985. * @returns the unmodified current Vector4
  3986. */
  3987. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3988. result.x += this.x * scale;
  3989. result.y += this.y * scale;
  3990. result.z += this.z * scale;
  3991. result.w += this.w * scale;
  3992. return this;
  3993. };
  3994. /**
  3995. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3996. */
  3997. Vector4.prototype.equals = function (otherVector) {
  3998. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3999. };
  4000. /**
  4001. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4002. */
  4003. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4004. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4005. return otherVector
  4006. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4007. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4008. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4009. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4010. };
  4011. /**
  4012. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4013. */
  4014. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4015. return this.x === x && this.y === y && this.z === z && this.w === w;
  4016. };
  4017. /**
  4018. * Multiplies in place the current Vector4 by the given one.
  4019. * Returns the updated Vector4.
  4020. */
  4021. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4022. this.x *= otherVector.x;
  4023. this.y *= otherVector.y;
  4024. this.z *= otherVector.z;
  4025. this.w *= otherVector.w;
  4026. return this;
  4027. };
  4028. /**
  4029. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4030. */
  4031. Vector4.prototype.multiply = function (otherVector) {
  4032. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4033. };
  4034. /**
  4035. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4036. * Returns the current Vector4.
  4037. */
  4038. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4039. result.x = this.x * otherVector.x;
  4040. result.y = this.y * otherVector.y;
  4041. result.z = this.z * otherVector.z;
  4042. result.w = this.w * otherVector.w;
  4043. return this;
  4044. };
  4045. /**
  4046. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4047. */
  4048. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4049. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4050. };
  4051. /**
  4052. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4053. */
  4054. Vector4.prototype.divide = function (otherVector) {
  4055. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4056. };
  4057. /**
  4058. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4059. * Returns the current Vector4.
  4060. */
  4061. Vector4.prototype.divideToRef = function (otherVector, result) {
  4062. result.x = this.x / otherVector.x;
  4063. result.y = this.y / otherVector.y;
  4064. result.z = this.z / otherVector.z;
  4065. result.w = this.w / otherVector.w;
  4066. return this;
  4067. };
  4068. /**
  4069. * Divides the current Vector3 coordinates by the given ones.
  4070. * @returns the updated Vector3.
  4071. */
  4072. Vector4.prototype.divideInPlace = function (otherVector) {
  4073. return this.divideToRef(otherVector, this);
  4074. };
  4075. /**
  4076. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4077. * @param other defines the second operand
  4078. * @returns the current updated Vector4
  4079. */
  4080. Vector4.prototype.minimizeInPlace = function (other) {
  4081. if (other.x < this.x)
  4082. this.x = other.x;
  4083. if (other.y < this.y)
  4084. this.y = other.y;
  4085. if (other.z < this.z)
  4086. this.z = other.z;
  4087. if (other.w < this.w)
  4088. this.w = other.w;
  4089. return this;
  4090. };
  4091. /**
  4092. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4093. * @param other defines the second operand
  4094. * @returns the current updated Vector4
  4095. */
  4096. Vector4.prototype.maximizeInPlace = function (other) {
  4097. if (other.x > this.x)
  4098. this.x = other.x;
  4099. if (other.y > this.y)
  4100. this.y = other.y;
  4101. if (other.z > this.z)
  4102. this.z = other.z;
  4103. if (other.w > this.w)
  4104. this.w = other.w;
  4105. return this;
  4106. };
  4107. /**
  4108. * Gets a new Vector4 from current Vector4 floored values
  4109. * @returns a new Vector4
  4110. */
  4111. Vector4.prototype.floor = function () {
  4112. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4113. };
  4114. /**
  4115. * Gets a new Vector4 from current Vector3 floored values
  4116. * @returns a new Vector4
  4117. */
  4118. Vector4.prototype.fract = function () {
  4119. 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));
  4120. };
  4121. // Properties
  4122. /**
  4123. * Returns the Vector4 length (float).
  4124. */
  4125. Vector4.prototype.length = function () {
  4126. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4127. };
  4128. /**
  4129. * Returns the Vector4 squared length (float).
  4130. */
  4131. Vector4.prototype.lengthSquared = function () {
  4132. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4133. };
  4134. // Methods
  4135. /**
  4136. * Normalizes in place the Vector4.
  4137. * Returns the updated Vector4.
  4138. */
  4139. Vector4.prototype.normalize = function () {
  4140. var len = this.length();
  4141. if (len === 0)
  4142. return this;
  4143. var num = 1.0 / len;
  4144. this.x *= num;
  4145. this.y *= num;
  4146. this.z *= num;
  4147. this.w *= num;
  4148. return this;
  4149. };
  4150. /**
  4151. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4152. */
  4153. Vector4.prototype.toVector3 = function () {
  4154. return new Vector3(this.x, this.y, this.z);
  4155. };
  4156. /**
  4157. * Returns a new Vector4 copied from the current one.
  4158. */
  4159. Vector4.prototype.clone = function () {
  4160. return new Vector4(this.x, this.y, this.z, this.w);
  4161. };
  4162. /**
  4163. * Updates the current Vector4 with the given one coordinates.
  4164. * Returns the updated Vector4.
  4165. */
  4166. Vector4.prototype.copyFrom = function (source) {
  4167. this.x = source.x;
  4168. this.y = source.y;
  4169. this.z = source.z;
  4170. this.w = source.w;
  4171. return this;
  4172. };
  4173. /**
  4174. * Updates the current Vector4 coordinates with the given floats.
  4175. * Returns the updated Vector4.
  4176. */
  4177. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4178. this.x = x;
  4179. this.y = y;
  4180. this.z = z;
  4181. this.w = w;
  4182. return this;
  4183. };
  4184. /**
  4185. * Updates the current Vector4 coordinates with the given floats.
  4186. * Returns the updated Vector4.
  4187. */
  4188. Vector4.prototype.set = function (x, y, z, w) {
  4189. return this.copyFromFloats(x, y, z, w);
  4190. };
  4191. // Statics
  4192. /**
  4193. * Returns a new Vector4 set from the starting index of the given array.
  4194. */
  4195. Vector4.FromArray = function (array, offset) {
  4196. if (!offset) {
  4197. offset = 0;
  4198. }
  4199. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4200. };
  4201. /**
  4202. * Updates the given vector "result" from the starting index of the given array.
  4203. */
  4204. Vector4.FromArrayToRef = function (array, offset, result) {
  4205. result.x = array[offset];
  4206. result.y = array[offset + 1];
  4207. result.z = array[offset + 2];
  4208. result.w = array[offset + 3];
  4209. };
  4210. /**
  4211. * Updates the given vector "result" from the starting index of the given Float32Array.
  4212. */
  4213. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4214. Vector4.FromArrayToRef(array, offset, result);
  4215. };
  4216. /**
  4217. * Updates the given vector "result" coordinates from the given floats.
  4218. */
  4219. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = w;
  4224. };
  4225. /**
  4226. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4227. */
  4228. Vector4.Zero = function () {
  4229. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4230. };
  4231. /**
  4232. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4233. */
  4234. Vector4.One = function () {
  4235. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4236. };
  4237. /**
  4238. * Returns a new normalized Vector4 from the given one.
  4239. */
  4240. Vector4.Normalize = function (vector) {
  4241. var result = Vector4.Zero();
  4242. Vector4.NormalizeToRef(vector, result);
  4243. return result;
  4244. };
  4245. /**
  4246. * Updates the given vector "result" from the normalization of the given one.
  4247. */
  4248. Vector4.NormalizeToRef = function (vector, result) {
  4249. result.copyFrom(vector);
  4250. result.normalize();
  4251. };
  4252. Vector4.Minimize = function (left, right) {
  4253. var min = left.clone();
  4254. min.minimizeInPlace(right);
  4255. return min;
  4256. };
  4257. Vector4.Maximize = function (left, right) {
  4258. var max = left.clone();
  4259. max.maximizeInPlace(right);
  4260. return max;
  4261. };
  4262. /**
  4263. * Returns the distance (float) between the vectors "value1" and "value2".
  4264. */
  4265. Vector4.Distance = function (value1, value2) {
  4266. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4267. };
  4268. /**
  4269. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4270. */
  4271. Vector4.DistanceSquared = function (value1, value2) {
  4272. var x = value1.x - value2.x;
  4273. var y = value1.y - value2.y;
  4274. var z = value1.z - value2.z;
  4275. var w = value1.w - value2.w;
  4276. return (x * x) + (y * y) + (z * z) + (w * w);
  4277. };
  4278. /**
  4279. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4280. */
  4281. Vector4.Center = function (value1, value2) {
  4282. var center = value1.add(value2);
  4283. center.scaleInPlace(0.5);
  4284. return center;
  4285. };
  4286. /**
  4287. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4288. * This methods computes transformed normalized direction vectors only.
  4289. */
  4290. Vector4.TransformNormal = function (vector, transformation) {
  4291. var result = Vector4.Zero();
  4292. Vector4.TransformNormalToRef(vector, transformation, result);
  4293. return result;
  4294. };
  4295. /**
  4296. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4297. * This methods computes transformed normalized direction vectors only.
  4298. */
  4299. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4300. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4301. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4302. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4303. result.x = x;
  4304. result.y = y;
  4305. result.z = z;
  4306. result.w = vector.w;
  4307. };
  4308. /**
  4309. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4310. * This methods computes transformed normalized direction vectors only.
  4311. */
  4312. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4313. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4314. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4315. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4316. result.w = w;
  4317. };
  4318. return Vector4;
  4319. }());
  4320. BABYLON.Vector4 = Vector4;
  4321. var Size = /** @class */ (function () {
  4322. /**
  4323. * Creates a Size object from the given width and height (floats).
  4324. */
  4325. function Size(width, height) {
  4326. this.width = width;
  4327. this.height = height;
  4328. }
  4329. // Returns a string with the Size width and height.
  4330. Size.prototype.toString = function () {
  4331. return "{W: " + this.width + ", H: " + this.height + "}";
  4332. };
  4333. /**
  4334. * Returns the string "Size"
  4335. */
  4336. Size.prototype.getClassName = function () {
  4337. return "Size";
  4338. };
  4339. /**
  4340. * Returns the Size hash code.
  4341. */
  4342. Size.prototype.getHashCode = function () {
  4343. var hash = this.width || 0;
  4344. hash = (hash * 397) ^ (this.height || 0);
  4345. return hash;
  4346. };
  4347. /**
  4348. * Updates the current size from the given one.
  4349. * Returns the updated Size.
  4350. */
  4351. Size.prototype.copyFrom = function (src) {
  4352. this.width = src.width;
  4353. this.height = src.height;
  4354. };
  4355. /**
  4356. * Updates in place the current Size from the given floats.
  4357. * Returns the updated Size.
  4358. */
  4359. Size.prototype.copyFromFloats = function (width, height) {
  4360. this.width = width;
  4361. this.height = height;
  4362. return this;
  4363. };
  4364. /**
  4365. * Updates in place the current Size from the given floats.
  4366. * Returns the updated Size.
  4367. */
  4368. Size.prototype.set = function (width, height) {
  4369. return this.copyFromFloats(width, height);
  4370. };
  4371. /**
  4372. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4373. */
  4374. Size.prototype.multiplyByFloats = function (w, h) {
  4375. return new Size(this.width * w, this.height * h);
  4376. };
  4377. /**
  4378. * Returns a new Size copied from the given one.
  4379. */
  4380. Size.prototype.clone = function () {
  4381. return new Size(this.width, this.height);
  4382. };
  4383. /**
  4384. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4385. */
  4386. Size.prototype.equals = function (other) {
  4387. if (!other) {
  4388. return false;
  4389. }
  4390. return (this.width === other.width) && (this.height === other.height);
  4391. };
  4392. Object.defineProperty(Size.prototype, "surface", {
  4393. /**
  4394. * Returns the surface of the Size : width * height (float).
  4395. */
  4396. get: function () {
  4397. return this.width * this.height;
  4398. },
  4399. enumerable: true,
  4400. configurable: true
  4401. });
  4402. /**
  4403. * Returns a new Size set to (0.0, 0.0)
  4404. */
  4405. Size.Zero = function () {
  4406. return new Size(0.0, 0.0);
  4407. };
  4408. /**
  4409. * Returns a new Size set as the addition result of the current Size and the given one.
  4410. */
  4411. Size.prototype.add = function (otherSize) {
  4412. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4413. return r;
  4414. };
  4415. /**
  4416. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4417. */
  4418. Size.prototype.subtract = function (otherSize) {
  4419. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4420. return r;
  4421. };
  4422. /**
  4423. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4424. */
  4425. Size.Lerp = function (start, end, amount) {
  4426. var w = start.width + ((end.width - start.width) * amount);
  4427. var h = start.height + ((end.height - start.height) * amount);
  4428. return new Size(w, h);
  4429. };
  4430. return Size;
  4431. }());
  4432. BABYLON.Size = Size;
  4433. /**
  4434. * Class used to store quaternion data
  4435. * @see https://en.wikipedia.org/wiki/Quaternion
  4436. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4437. */
  4438. var Quaternion = /** @class */ (function () {
  4439. /**
  4440. * Creates a new Quaternion from the given floats
  4441. * @param x defines the first component (0 by default)
  4442. * @param y defines the second component (0 by default)
  4443. * @param z defines the third component (0 by default)
  4444. * @param w defines the fourth component (1.0 by default)
  4445. */
  4446. function Quaternion(
  4447. /** defines the first component (0 by default) */
  4448. x,
  4449. /** defines the second component (0 by default) */
  4450. y,
  4451. /** defines the third component (0 by default) */
  4452. z,
  4453. /** defines the fourth component (1.0 by default) */
  4454. w) {
  4455. if (x === void 0) { x = 0.0; }
  4456. if (y === void 0) { y = 0.0; }
  4457. if (z === void 0) { z = 0.0; }
  4458. if (w === void 0) { w = 1.0; }
  4459. this.x = x;
  4460. this.y = y;
  4461. this.z = z;
  4462. this.w = w;
  4463. }
  4464. /**
  4465. * Gets a string representation for the current quaternion
  4466. * @returns a string with the Quaternion coordinates
  4467. */
  4468. Quaternion.prototype.toString = function () {
  4469. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4470. };
  4471. /**
  4472. * Gets the class name of the quaternion
  4473. * @returns the string "Quaternion"
  4474. */
  4475. Quaternion.prototype.getClassName = function () {
  4476. return "Quaternion";
  4477. };
  4478. /**
  4479. * Gets a hash code for this quaternion
  4480. * @returns the quaternion hash code
  4481. */
  4482. Quaternion.prototype.getHashCode = function () {
  4483. var hash = this.x || 0;
  4484. hash = (hash * 397) ^ (this.y || 0);
  4485. hash = (hash * 397) ^ (this.z || 0);
  4486. hash = (hash * 397) ^ (this.w || 0);
  4487. return hash;
  4488. };
  4489. /**
  4490. * Copy the quaternion to an array
  4491. * @returns a new array populated with 4 elements from the quaternion coordinates
  4492. */
  4493. Quaternion.prototype.asArray = function () {
  4494. return [this.x, this.y, this.z, this.w];
  4495. };
  4496. /**
  4497. * Check if two quaternions are equals
  4498. * @param otherQuaternion defines the second operand
  4499. * @return true if the current quaternion and the given one coordinates are strictly equals
  4500. */
  4501. Quaternion.prototype.equals = function (otherQuaternion) {
  4502. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4503. };
  4504. /**
  4505. * Clone the current quaternion
  4506. * @returns a new quaternion copied from the current one
  4507. */
  4508. Quaternion.prototype.clone = function () {
  4509. return new Quaternion(this.x, this.y, this.z, this.w);
  4510. };
  4511. /**
  4512. * Copy a quaternion to the current one
  4513. * @param other defines the other quaternion
  4514. * @returns the updated current quaternion
  4515. */
  4516. Quaternion.prototype.copyFrom = function (other) {
  4517. this.x = other.x;
  4518. this.y = other.y;
  4519. this.z = other.z;
  4520. this.w = other.w;
  4521. return this;
  4522. };
  4523. /**
  4524. * Updates the current quaternion with the given float coordinates
  4525. * @param x defines the x coordinate
  4526. * @param y defines the y coordinate
  4527. * @param z defines the z coordinate
  4528. * @param w defines the w coordinate
  4529. * @returns the updated current quaternion
  4530. */
  4531. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4532. this.x = x;
  4533. this.y = y;
  4534. this.z = z;
  4535. this.w = w;
  4536. return this;
  4537. };
  4538. /**
  4539. * Updates the current quaternion from the given float coordinates
  4540. * @param x defines the x coordinate
  4541. * @param y defines the y coordinate
  4542. * @param z defines the z coordinate
  4543. * @param w defines the w coordinate
  4544. * @returns the updated current quaternion
  4545. */
  4546. Quaternion.prototype.set = function (x, y, z, w) {
  4547. return this.copyFromFloats(x, y, z, w);
  4548. };
  4549. /**
  4550. * Adds two quaternions
  4551. * @param other defines the second operand
  4552. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4553. */
  4554. Quaternion.prototype.add = function (other) {
  4555. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4556. };
  4557. /**
  4558. * Add a quaternion to the current one
  4559. * @param other defines the quaternion to add
  4560. * @returns the current quaternion
  4561. */
  4562. Quaternion.prototype.addInPlace = function (other) {
  4563. this.x += other.x;
  4564. this.y += other.y;
  4565. this.z += other.z;
  4566. this.w += other.w;
  4567. return this;
  4568. };
  4569. /**
  4570. * Subtract two quaternions
  4571. * @param other defines the second operand
  4572. * @returns a new quaternion as the subtraction result of the given one from the current one
  4573. */
  4574. Quaternion.prototype.subtract = function (other) {
  4575. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4576. };
  4577. /**
  4578. * Multiplies the current quaternion by a scale factor
  4579. * @param value defines the scale factor
  4580. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4581. */
  4582. Quaternion.prototype.scale = function (value) {
  4583. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4584. };
  4585. /**
  4586. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4587. * @param scale defines the scale factor
  4588. * @param result defines the Quaternion object where to store the result
  4589. * @returns the unmodified current quaternion
  4590. */
  4591. Quaternion.prototype.scaleToRef = function (scale, result) {
  4592. result.x = this.x * scale;
  4593. result.y = this.y * scale;
  4594. result.z = this.z * scale;
  4595. result.w = this.w * scale;
  4596. return this;
  4597. };
  4598. /**
  4599. * Multiplies in place the current quaternion by a scale factor
  4600. * @param value defines the scale factor
  4601. * @returns the current modified quaternion
  4602. */
  4603. Quaternion.prototype.scaleInPlace = function (value) {
  4604. this.x *= value;
  4605. this.y *= value;
  4606. this.z *= value;
  4607. this.w *= value;
  4608. return this;
  4609. };
  4610. /**
  4611. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4612. * @param scale defines the scale factor
  4613. * @param result defines the Quaternion object where to store the result
  4614. * @returns the unmodified current quaternion
  4615. */
  4616. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4617. result.x += this.x * scale;
  4618. result.y += this.y * scale;
  4619. result.z += this.z * scale;
  4620. result.w += this.w * scale;
  4621. return this;
  4622. };
  4623. /**
  4624. * Multiplies two quaternions
  4625. * @param q1 defines the second operand
  4626. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4627. */
  4628. Quaternion.prototype.multiply = function (q1) {
  4629. var result = new Quaternion(0, 0, 0, 1.0);
  4630. this.multiplyToRef(q1, result);
  4631. return result;
  4632. };
  4633. /**
  4634. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4635. * @param q1 defines the second operand
  4636. * @param result defines the target quaternion
  4637. * @returns the current quaternion
  4638. */
  4639. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4640. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4641. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4642. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4643. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4644. result.copyFromFloats(x, y, z, w);
  4645. return this;
  4646. };
  4647. /**
  4648. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4649. * @param q1 defines the second operand
  4650. * @returns the currentupdated quaternion
  4651. */
  4652. Quaternion.prototype.multiplyInPlace = function (q1) {
  4653. this.multiplyToRef(q1, this);
  4654. return this;
  4655. };
  4656. /**
  4657. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4658. * @param ref defines the target quaternion
  4659. * @returns the current quaternion
  4660. */
  4661. Quaternion.prototype.conjugateToRef = function (ref) {
  4662. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4663. return this;
  4664. };
  4665. /**
  4666. * Conjugates in place (1-q) the current quaternion
  4667. * @returns the current updated quaternion
  4668. */
  4669. Quaternion.prototype.conjugateInPlace = function () {
  4670. this.x *= -1;
  4671. this.y *= -1;
  4672. this.z *= -1;
  4673. return this;
  4674. };
  4675. /**
  4676. * Conjugates in place (1-q) the current quaternion
  4677. * @returns a new quaternion
  4678. */
  4679. Quaternion.prototype.conjugate = function () {
  4680. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4681. return result;
  4682. };
  4683. /**
  4684. * Gets length of current quaternion
  4685. * @returns the quaternion length (float)
  4686. */
  4687. Quaternion.prototype.length = function () {
  4688. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4689. };
  4690. /**
  4691. * Normalize in place the current quaternion
  4692. * @returns the current updated quaternion
  4693. */
  4694. Quaternion.prototype.normalize = function () {
  4695. var length = 1.0 / this.length();
  4696. this.x *= length;
  4697. this.y *= length;
  4698. this.z *= length;
  4699. this.w *= length;
  4700. return this;
  4701. };
  4702. /**
  4703. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4704. * @param order is a reserved parameter and is ignore for now
  4705. * @returns a new Vector3 containing the Euler angles
  4706. */
  4707. Quaternion.prototype.toEulerAngles = function (order) {
  4708. if (order === void 0) { order = "YZX"; }
  4709. var result = Vector3.Zero();
  4710. this.toEulerAnglesToRef(result, order);
  4711. return result;
  4712. };
  4713. /**
  4714. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4715. * @param result defines the vector which will be filled with the Euler angles
  4716. * @param order is a reserved parameter and is ignore for now
  4717. * @returns the current unchanged quaternion
  4718. */
  4719. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4720. if (order === void 0) { order = "YZX"; }
  4721. var qz = this.z;
  4722. var qx = this.x;
  4723. var qy = this.y;
  4724. var qw = this.w;
  4725. var sqw = qw * qw;
  4726. var sqz = qz * qz;
  4727. var sqx = qx * qx;
  4728. var sqy = qy * qy;
  4729. var zAxisY = qy * qz - qx * qw;
  4730. var limit = .4999999;
  4731. if (zAxisY < -limit) {
  4732. result.y = 2 * Math.atan2(qy, qw);
  4733. result.x = Math.PI / 2;
  4734. result.z = 0;
  4735. }
  4736. else if (zAxisY > limit) {
  4737. result.y = 2 * Math.atan2(qy, qw);
  4738. result.x = -Math.PI / 2;
  4739. result.z = 0;
  4740. }
  4741. else {
  4742. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4743. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4744. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4745. }
  4746. return this;
  4747. };
  4748. /**
  4749. * Updates the given rotation matrix with the current quaternion values
  4750. * @param result defines the target matrix
  4751. * @returns the current unchanged quaternion
  4752. */
  4753. Quaternion.prototype.toRotationMatrix = function (result) {
  4754. var xx = this.x * this.x;
  4755. var yy = this.y * this.y;
  4756. var zz = this.z * this.z;
  4757. var xy = this.x * this.y;
  4758. var zw = this.z * this.w;
  4759. var zx = this.z * this.x;
  4760. var yw = this.y * this.w;
  4761. var yz = this.y * this.z;
  4762. var xw = this.x * this.w;
  4763. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4764. result.m[1] = 2.0 * (xy + zw);
  4765. result.m[2] = 2.0 * (zx - yw);
  4766. result.m[3] = 0;
  4767. result.m[4] = 2.0 * (xy - zw);
  4768. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4769. result.m[6] = 2.0 * (yz + xw);
  4770. result.m[7] = 0;
  4771. result.m[8] = 2.0 * (zx + yw);
  4772. result.m[9] = 2.0 * (yz - xw);
  4773. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4774. result.m[11] = 0;
  4775. result.m[12] = 0;
  4776. result.m[13] = 0;
  4777. result.m[14] = 0;
  4778. result.m[15] = 1.0;
  4779. result._markAsUpdated();
  4780. return this;
  4781. };
  4782. /**
  4783. * Updates the current quaternion from the given rotation matrix values
  4784. * @param matrix defines the source matrix
  4785. * @returns the current updated quaternion
  4786. */
  4787. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4788. Quaternion.FromRotationMatrixToRef(matrix, this);
  4789. return this;
  4790. };
  4791. // Statics
  4792. /**
  4793. * Creates a new quaternion from a rotation matrix
  4794. * @param matrix defines the source matrix
  4795. * @returns a new quaternion created from the given rotation matrix values
  4796. */
  4797. Quaternion.FromRotationMatrix = function (matrix) {
  4798. var result = new Quaternion();
  4799. Quaternion.FromRotationMatrixToRef(matrix, result);
  4800. return result;
  4801. };
  4802. /**
  4803. * Updates the given quaternion with the given rotation matrix values
  4804. * @param matrix defines the source matrix
  4805. * @param result defines the target quaternion
  4806. */
  4807. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4808. var data = matrix.m;
  4809. var m11 = data[0], m12 = data[4], m13 = data[8];
  4810. var m21 = data[1], m22 = data[5], m23 = data[9];
  4811. var m31 = data[2], m32 = data[6], m33 = data[10];
  4812. var trace = m11 + m22 + m33;
  4813. var s;
  4814. if (trace > 0) {
  4815. s = 0.5 / Math.sqrt(trace + 1.0);
  4816. result.w = 0.25 / s;
  4817. result.x = (m32 - m23) * s;
  4818. result.y = (m13 - m31) * s;
  4819. result.z = (m21 - m12) * s;
  4820. }
  4821. else if (m11 > m22 && m11 > m33) {
  4822. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4823. result.w = (m32 - m23) / s;
  4824. result.x = 0.25 * s;
  4825. result.y = (m12 + m21) / s;
  4826. result.z = (m13 + m31) / s;
  4827. }
  4828. else if (m22 > m33) {
  4829. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4830. result.w = (m13 - m31) / s;
  4831. result.x = (m12 + m21) / s;
  4832. result.y = 0.25 * s;
  4833. result.z = (m23 + m32) / s;
  4834. }
  4835. else {
  4836. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4837. result.w = (m21 - m12) / s;
  4838. result.x = (m13 + m31) / s;
  4839. result.y = (m23 + m32) / s;
  4840. result.z = 0.25 * s;
  4841. }
  4842. };
  4843. /**
  4844. * Returns the dot product (float) between the quaternions "left" and "right"
  4845. * @param left defines the left operand
  4846. * @param right defines the right operand
  4847. * @returns the dot product
  4848. */
  4849. Quaternion.Dot = function (left, right) {
  4850. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4851. };
  4852. /**
  4853. * Checks if the two quaternions are close to each other
  4854. * @param quat0 defines the first quaternion to check
  4855. * @param quat1 defines the second quaternion to check
  4856. * @returns true if the two quaternions are close to each other
  4857. */
  4858. Quaternion.AreClose = function (quat0, quat1) {
  4859. var dot = Quaternion.Dot(quat0, quat1);
  4860. return dot >= 0;
  4861. };
  4862. /**
  4863. * Creates an empty quaternion
  4864. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4865. */
  4866. Quaternion.Zero = function () {
  4867. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4868. };
  4869. /**
  4870. * Inverse a given quaternion
  4871. * @param q defines the source quaternion
  4872. * @returns a new quaternion as the inverted current quaternion
  4873. */
  4874. Quaternion.Inverse = function (q) {
  4875. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4876. };
  4877. /**
  4878. * Creates an identity quaternion
  4879. * @returns the identity quaternion
  4880. */
  4881. Quaternion.Identity = function () {
  4882. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4883. };
  4884. /**
  4885. * Gets a boolean indicating if the given quaternion is identity
  4886. * @param quaternion defines the quaternion to check
  4887. * @returns true if the quaternion is identity
  4888. */
  4889. Quaternion.IsIdentity = function (quaternion) {
  4890. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4891. };
  4892. /**
  4893. * Creates a quaternion from a rotation around an axis
  4894. * @param axis defines the axis to use
  4895. * @param angle defines the angle to use
  4896. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4897. */
  4898. Quaternion.RotationAxis = function (axis, angle) {
  4899. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4900. };
  4901. /**
  4902. * Creates a rotation around an axis and stores it into the given quaternion
  4903. * @param axis defines the axis to use
  4904. * @param angle defines the angle to use
  4905. * @param result defines the target quaternion
  4906. * @returns the target quaternion
  4907. */
  4908. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4909. var sin = Math.sin(angle / 2);
  4910. axis.normalize();
  4911. result.w = Math.cos(angle / 2);
  4912. result.x = axis.x * sin;
  4913. result.y = axis.y * sin;
  4914. result.z = axis.z * sin;
  4915. return result;
  4916. };
  4917. /**
  4918. * Creates a new quaternion from data stored into an array
  4919. * @param array defines the data source
  4920. * @param offset defines the offset in the source array where the data starts
  4921. * @returns a new quaternion
  4922. */
  4923. Quaternion.FromArray = function (array, offset) {
  4924. if (!offset) {
  4925. offset = 0;
  4926. }
  4927. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4928. };
  4929. /**
  4930. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4931. * @param yaw defines the rotation around Y axis
  4932. * @param pitch defines the rotation around X axis
  4933. * @param roll defines the rotation around Z axis
  4934. * @returns the new quaternion
  4935. */
  4936. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4937. var q = new Quaternion();
  4938. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4939. return q;
  4940. };
  4941. /**
  4942. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4943. * @param yaw defines the rotation around Y axis
  4944. * @param pitch defines the rotation around X axis
  4945. * @param roll defines the rotation around Z axis
  4946. * @param result defines the target quaternion
  4947. */
  4948. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4949. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4950. var halfRoll = roll * 0.5;
  4951. var halfPitch = pitch * 0.5;
  4952. var halfYaw = yaw * 0.5;
  4953. var sinRoll = Math.sin(halfRoll);
  4954. var cosRoll = Math.cos(halfRoll);
  4955. var sinPitch = Math.sin(halfPitch);
  4956. var cosPitch = Math.cos(halfPitch);
  4957. var sinYaw = Math.sin(halfYaw);
  4958. var cosYaw = Math.cos(halfYaw);
  4959. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4960. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4961. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4962. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4963. };
  4964. /**
  4965. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4966. * @param alpha defines the rotation around first axis
  4967. * @param beta defines the rotation around second axis
  4968. * @param gamma defines the rotation around third axis
  4969. * @returns the new quaternion
  4970. */
  4971. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4972. var result = new Quaternion();
  4973. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4974. return result;
  4975. };
  4976. /**
  4977. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4978. * @param alpha defines the rotation around first axis
  4979. * @param beta defines the rotation around second axis
  4980. * @param gamma defines the rotation around third axis
  4981. * @param result defines the target quaternion
  4982. */
  4983. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4984. // Produces a quaternion from Euler angles in the z-x-z orientation
  4985. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4986. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4987. var halfBeta = beta * 0.5;
  4988. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4989. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4990. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4991. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4992. };
  4993. /**
  4994. * 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)
  4995. * @param axis1 defines the first axis
  4996. * @param axis2 defines the second axis
  4997. * @param axis3 defines the third axis
  4998. * @returns the new quaternion
  4999. */
  5000. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5001. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5002. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5003. return quat;
  5004. };
  5005. /**
  5006. * 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
  5007. * @param axis1 defines the first axis
  5008. * @param axis2 defines the second axis
  5009. * @param axis3 defines the third axis
  5010. * @param ref defines the target quaternion
  5011. */
  5012. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5013. var rotMat = MathTmp.Matrix[0];
  5014. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5015. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5016. };
  5017. /**
  5018. * Interpolates between two quaternions
  5019. * @param left defines first quaternion
  5020. * @param right defines second quaternion
  5021. * @param amount defines the gradient to use
  5022. * @returns the new interpolated quaternion
  5023. */
  5024. Quaternion.Slerp = function (left, right, amount) {
  5025. var result = Quaternion.Identity();
  5026. Quaternion.SlerpToRef(left, right, amount, result);
  5027. return result;
  5028. };
  5029. /**
  5030. * Interpolates between two quaternions and stores it into a target quaternion
  5031. * @param left defines first quaternion
  5032. * @param right defines second quaternion
  5033. * @param amount defines the gradient to use
  5034. * @param result defines the target quaternion
  5035. */
  5036. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5037. var num2;
  5038. var num3;
  5039. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5040. var flag = false;
  5041. if (num4 < 0) {
  5042. flag = true;
  5043. num4 = -num4;
  5044. }
  5045. if (num4 > 0.999999) {
  5046. num3 = 1 - amount;
  5047. num2 = flag ? -amount : amount;
  5048. }
  5049. else {
  5050. var num5 = Math.acos(num4);
  5051. var num6 = (1.0 / Math.sin(num5));
  5052. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5053. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5054. }
  5055. result.x = (num3 * left.x) + (num2 * right.x);
  5056. result.y = (num3 * left.y) + (num2 * right.y);
  5057. result.z = (num3 * left.z) + (num2 * right.z);
  5058. result.w = (num3 * left.w) + (num2 * right.w);
  5059. };
  5060. /**
  5061. * Interpolate between two quaternions using Hermite interpolation
  5062. * @param value1 defines first quaternion
  5063. * @param tangent1 defines the incoming tangent
  5064. * @param value2 defines second quaternion
  5065. * @param tangent2 defines the outgoing tangent
  5066. * @param amount defines the target quaternion
  5067. * @returns the new interpolated quaternion
  5068. */
  5069. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5070. var squared = amount * amount;
  5071. var cubed = amount * squared;
  5072. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5073. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5074. var part3 = (cubed - (2.0 * squared)) + amount;
  5075. var part4 = cubed - squared;
  5076. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5077. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5078. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5079. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5080. return new Quaternion(x, y, z, w);
  5081. };
  5082. return Quaternion;
  5083. }());
  5084. BABYLON.Quaternion = Quaternion;
  5085. /**
  5086. * Class used to store matrix data (4x4)
  5087. */
  5088. var Matrix = /** @class */ (function () {
  5089. /**
  5090. * Creates an empty matrix (filled with zeros)
  5091. */
  5092. function Matrix() {
  5093. this._isIdentity = false;
  5094. this._isIdentityDirty = true;
  5095. /**
  5096. * Gets or sets the internal data of the matrix
  5097. */
  5098. this.m = new Float32Array(16);
  5099. this._markAsUpdated();
  5100. }
  5101. /** @hidden */
  5102. Matrix.prototype._markAsUpdated = function () {
  5103. this.updateFlag = Matrix._updateFlagSeed++;
  5104. this._isIdentityDirty = true;
  5105. };
  5106. // Properties
  5107. /**
  5108. * Check if the current matrix is indentity
  5109. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5110. * @returns true is the matrix is the identity matrix
  5111. */
  5112. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5113. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5114. if (this._isIdentityDirty) {
  5115. this._isIdentityDirty = false;
  5116. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5117. this._isIdentity = false;
  5118. }
  5119. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5120. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5121. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5122. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5123. this._isIdentity = false;
  5124. }
  5125. else {
  5126. this._isIdentity = true;
  5127. }
  5128. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5129. this._isIdentity = false;
  5130. }
  5131. }
  5132. return this._isIdentity;
  5133. };
  5134. /**
  5135. * Gets the determinant of the matrix
  5136. * @returns the matrix determinant
  5137. */
  5138. Matrix.prototype.determinant = function () {
  5139. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5140. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5141. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5142. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5143. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5144. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5145. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5146. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5147. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5148. };
  5149. // Methods
  5150. /**
  5151. * Returns the matrix as a Float32Array
  5152. * @returns the matrix underlying array
  5153. */
  5154. Matrix.prototype.toArray = function () {
  5155. return this.m;
  5156. };
  5157. /**
  5158. * Returns the matrix as a Float32Array
  5159. * @returns the matrix underlying array.
  5160. */
  5161. Matrix.prototype.asArray = function () {
  5162. return this.toArray();
  5163. };
  5164. /**
  5165. * Inverts the current matrix in place
  5166. * @returns the current inverted matrix
  5167. */
  5168. Matrix.prototype.invert = function () {
  5169. this.invertToRef(this);
  5170. return this;
  5171. };
  5172. /**
  5173. * Sets all the matrix elements to zero
  5174. * @returns the current matrix
  5175. */
  5176. Matrix.prototype.reset = function () {
  5177. for (var index = 0; index < 16; index++) {
  5178. this.m[index] = 0.0;
  5179. }
  5180. this._markAsUpdated();
  5181. return this;
  5182. };
  5183. /**
  5184. * Adds the current matrix with a second one
  5185. * @param other defines the matrix to add
  5186. * @returns a new matrix as the addition of the current matrix and the given one
  5187. */
  5188. Matrix.prototype.add = function (other) {
  5189. var result = new Matrix();
  5190. this.addToRef(other, result);
  5191. return result;
  5192. };
  5193. /**
  5194. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5195. * @param other defines the matrix to add
  5196. * @param result defines the target matrix
  5197. * @returns the current matrix
  5198. */
  5199. Matrix.prototype.addToRef = function (other, result) {
  5200. for (var index = 0; index < 16; index++) {
  5201. result.m[index] = this.m[index] + other.m[index];
  5202. }
  5203. result._markAsUpdated();
  5204. return this;
  5205. };
  5206. /**
  5207. * Adds in place the given matrix to the current matrix
  5208. * @param other defines the second operand
  5209. * @returns the current updated matrix
  5210. */
  5211. Matrix.prototype.addToSelf = function (other) {
  5212. for (var index = 0; index < 16; index++) {
  5213. this.m[index] += other.m[index];
  5214. }
  5215. this._markAsUpdated();
  5216. return this;
  5217. };
  5218. /**
  5219. * Sets the given matrix to the current inverted Matrix
  5220. * @param other defines the target matrix
  5221. * @returns the unmodified current matrix
  5222. */
  5223. Matrix.prototype.invertToRef = function (other) {
  5224. var l1 = this.m[0];
  5225. var l2 = this.m[1];
  5226. var l3 = this.m[2];
  5227. var l4 = this.m[3];
  5228. var l5 = this.m[4];
  5229. var l6 = this.m[5];
  5230. var l7 = this.m[6];
  5231. var l8 = this.m[7];
  5232. var l9 = this.m[8];
  5233. var l10 = this.m[9];
  5234. var l11 = this.m[10];
  5235. var l12 = this.m[11];
  5236. var l13 = this.m[12];
  5237. var l14 = this.m[13];
  5238. var l15 = this.m[14];
  5239. var l16 = this.m[15];
  5240. var l17 = (l11 * l16) - (l12 * l15);
  5241. var l18 = (l10 * l16) - (l12 * l14);
  5242. var l19 = (l10 * l15) - (l11 * l14);
  5243. var l20 = (l9 * l16) - (l12 * l13);
  5244. var l21 = (l9 * l15) - (l11 * l13);
  5245. var l22 = (l9 * l14) - (l10 * l13);
  5246. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5247. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5248. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5249. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5250. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5251. var l28 = (l7 * l16) - (l8 * l15);
  5252. var l29 = (l6 * l16) - (l8 * l14);
  5253. var l30 = (l6 * l15) - (l7 * l14);
  5254. var l31 = (l5 * l16) - (l8 * l13);
  5255. var l32 = (l5 * l15) - (l7 * l13);
  5256. var l33 = (l5 * l14) - (l6 * l13);
  5257. var l34 = (l7 * l12) - (l8 * l11);
  5258. var l35 = (l6 * l12) - (l8 * l10);
  5259. var l36 = (l6 * l11) - (l7 * l10);
  5260. var l37 = (l5 * l12) - (l8 * l9);
  5261. var l38 = (l5 * l11) - (l7 * l9);
  5262. var l39 = (l5 * l10) - (l6 * l9);
  5263. other.m[0] = l23 * l27;
  5264. other.m[4] = l24 * l27;
  5265. other.m[8] = l25 * l27;
  5266. other.m[12] = l26 * l27;
  5267. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5268. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5269. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5270. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5271. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5272. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5273. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5274. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5275. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5276. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5277. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5278. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5279. other._markAsUpdated();
  5280. return this;
  5281. };
  5282. /**
  5283. * Inserts the translation vector (using 3 floats) in the current matrix
  5284. * @param x defines the 1st component of the translation
  5285. * @param y defines the 2nd component of the translation
  5286. * @param z defines the 3rd component of the translation
  5287. * @returns the current updated matrix
  5288. */
  5289. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5290. this.m[12] = x;
  5291. this.m[13] = y;
  5292. this.m[14] = z;
  5293. this._markAsUpdated();
  5294. return this;
  5295. };
  5296. /**
  5297. * Inserts the translation vector in the current matrix
  5298. * @param vector3 defines the translation to insert
  5299. * @returns the current updated matrix
  5300. */
  5301. Matrix.prototype.setTranslation = function (vector3) {
  5302. this.m[12] = vector3.x;
  5303. this.m[13] = vector3.y;
  5304. this.m[14] = vector3.z;
  5305. this._markAsUpdated();
  5306. return this;
  5307. };
  5308. /**
  5309. * Gets the translation value of the current matrix
  5310. * @returns a new Vector3 as the extracted translation from the matrix
  5311. */
  5312. Matrix.prototype.getTranslation = function () {
  5313. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5314. };
  5315. /**
  5316. * Fill a Vector3 with the extracted translation from the matrix
  5317. * @param result defines the Vector3 where to store the translation
  5318. * @returns the current matrix
  5319. */
  5320. Matrix.prototype.getTranslationToRef = function (result) {
  5321. result.x = this.m[12];
  5322. result.y = this.m[13];
  5323. result.z = this.m[14];
  5324. return this;
  5325. };
  5326. /**
  5327. * Remove rotation and scaling part from the matrix
  5328. * @returns the updated matrix
  5329. */
  5330. Matrix.prototype.removeRotationAndScaling = function () {
  5331. this.setRowFromFloats(0, 1, 0, 0, 0);
  5332. this.setRowFromFloats(1, 0, 1, 0, 0);
  5333. this.setRowFromFloats(2, 0, 0, 1, 0);
  5334. return this;
  5335. };
  5336. /**
  5337. * Multiply two matrices
  5338. * @param other defines the second operand
  5339. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5340. */
  5341. Matrix.prototype.multiply = function (other) {
  5342. var result = new Matrix();
  5343. this.multiplyToRef(other, result);
  5344. return result;
  5345. };
  5346. /**
  5347. * Copy the current matrix from the given one
  5348. * @param other defines the source matrix
  5349. * @returns the current updated matrix
  5350. */
  5351. Matrix.prototype.copyFrom = function (other) {
  5352. for (var index = 0; index < 16; index++) {
  5353. this.m[index] = other.m[index];
  5354. }
  5355. this._markAsUpdated();
  5356. return this;
  5357. };
  5358. /**
  5359. * Populates the given array from the starting index with the current matrix values
  5360. * @param array defines the target array
  5361. * @param offset defines the offset in the target array where to start storing values
  5362. * @returns the current matrix
  5363. */
  5364. Matrix.prototype.copyToArray = function (array, offset) {
  5365. if (offset === void 0) { offset = 0; }
  5366. for (var index = 0; index < 16; index++) {
  5367. array[offset + index] = this.m[index];
  5368. }
  5369. return this;
  5370. };
  5371. /**
  5372. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5373. * @param other defines the second operand
  5374. * @param result defines the matrix where to store the multiplication
  5375. * @returns the current matrix
  5376. */
  5377. Matrix.prototype.multiplyToRef = function (other, result) {
  5378. this.multiplyToArray(other, result.m, 0);
  5379. result._markAsUpdated();
  5380. return this;
  5381. };
  5382. /**
  5383. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5384. * @param other defines the second operand
  5385. * @param result defines the array where to store the multiplication
  5386. * @param offset defines the offset in the target array where to start storing values
  5387. * @returns the current matrix
  5388. */
  5389. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5390. var tm0 = this.m[0];
  5391. var tm1 = this.m[1];
  5392. var tm2 = this.m[2];
  5393. var tm3 = this.m[3];
  5394. var tm4 = this.m[4];
  5395. var tm5 = this.m[5];
  5396. var tm6 = this.m[6];
  5397. var tm7 = this.m[7];
  5398. var tm8 = this.m[8];
  5399. var tm9 = this.m[9];
  5400. var tm10 = this.m[10];
  5401. var tm11 = this.m[11];
  5402. var tm12 = this.m[12];
  5403. var tm13 = this.m[13];
  5404. var tm14 = this.m[14];
  5405. var tm15 = this.m[15];
  5406. var om0 = other.m[0];
  5407. var om1 = other.m[1];
  5408. var om2 = other.m[2];
  5409. var om3 = other.m[3];
  5410. var om4 = other.m[4];
  5411. var om5 = other.m[5];
  5412. var om6 = other.m[6];
  5413. var om7 = other.m[7];
  5414. var om8 = other.m[8];
  5415. var om9 = other.m[9];
  5416. var om10 = other.m[10];
  5417. var om11 = other.m[11];
  5418. var om12 = other.m[12];
  5419. var om13 = other.m[13];
  5420. var om14 = other.m[14];
  5421. var om15 = other.m[15];
  5422. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5423. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5424. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5425. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5426. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5427. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5428. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5429. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5430. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5431. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5432. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5433. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5434. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5435. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5436. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5437. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5438. return this;
  5439. };
  5440. /**
  5441. * Check equality between this matrix and a second one
  5442. * @param value defines the second matrix to compare
  5443. * @returns true is the current matrix and the given one values are strictly equal
  5444. */
  5445. Matrix.prototype.equals = function (value) {
  5446. return value &&
  5447. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5448. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5449. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5450. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5451. };
  5452. /**
  5453. * Clone the current matrix
  5454. * @returns a new matrix from the current matrix
  5455. */
  5456. Matrix.prototype.clone = function () {
  5457. 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]);
  5458. };
  5459. /**
  5460. * Returns the name of the current matrix class
  5461. * @returns the string "Matrix"
  5462. */
  5463. Matrix.prototype.getClassName = function () {
  5464. return "Matrix";
  5465. };
  5466. /**
  5467. * Gets the hash code of the current matrix
  5468. * @returns the hash code
  5469. */
  5470. Matrix.prototype.getHashCode = function () {
  5471. var hash = this.m[0] || 0;
  5472. for (var i = 1; i < 16; i++) {
  5473. hash = (hash * 397) ^ (this.m[i] || 0);
  5474. }
  5475. return hash;
  5476. };
  5477. /**
  5478. * Decomposes the current Matrix into a translation, rotation and scaling components
  5479. * @param scale defines the scale vector3 given as a reference to update
  5480. * @param rotation defines the rotation quaternion given as a reference to update
  5481. * @param translation defines the translation vector3 given as a reference to update
  5482. * @returns true if operation was successful
  5483. */
  5484. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5485. if (translation) {
  5486. translation.x = this.m[12];
  5487. translation.y = this.m[13];
  5488. translation.z = this.m[14];
  5489. }
  5490. scale = scale || MathTmp.Vector3[0];
  5491. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5492. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5493. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5494. if (this.determinant() <= 0) {
  5495. scale.y *= -1;
  5496. }
  5497. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5498. if (rotation) {
  5499. rotation.x = 0;
  5500. rotation.y = 0;
  5501. rotation.z = 0;
  5502. rotation.w = 1;
  5503. }
  5504. return false;
  5505. }
  5506. if (rotation) {
  5507. 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]);
  5508. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5509. }
  5510. return true;
  5511. };
  5512. /**
  5513. * Gets specific row of the matrix
  5514. * @param index defines the number of the row to get
  5515. * @returns the index-th row of the current matrix as a new Vector4
  5516. */
  5517. Matrix.prototype.getRow = function (index) {
  5518. if (index < 0 || index > 3) {
  5519. return null;
  5520. }
  5521. var i = index * 4;
  5522. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5523. };
  5524. /**
  5525. * Sets the index-th row of the current matrix to the vector4 values
  5526. * @param index defines the number of the row to set
  5527. * @param row defines the target vector4
  5528. * @returns the updated current matrix
  5529. */
  5530. Matrix.prototype.setRow = function (index, row) {
  5531. if (index < 0 || index > 3) {
  5532. return this;
  5533. }
  5534. var i = index * 4;
  5535. this.m[i + 0] = row.x;
  5536. this.m[i + 1] = row.y;
  5537. this.m[i + 2] = row.z;
  5538. this.m[i + 3] = row.w;
  5539. this._markAsUpdated();
  5540. return this;
  5541. };
  5542. /**
  5543. * Compute the transpose of the matrix
  5544. * @returns the new transposed matrix
  5545. */
  5546. Matrix.prototype.transpose = function () {
  5547. return Matrix.Transpose(this);
  5548. };
  5549. /**
  5550. * Compute the transpose of the matrix and store it in a given matrix
  5551. * @param result defines the target matrix
  5552. * @returns the current matrix
  5553. */
  5554. Matrix.prototype.transposeToRef = function (result) {
  5555. Matrix.TransposeToRef(this, result);
  5556. return this;
  5557. };
  5558. /**
  5559. * Sets the index-th row of the current matrix with the given 4 x float values
  5560. * @param index defines the row index
  5561. * @param x defines the x component to set
  5562. * @param y defines the y component to set
  5563. * @param z defines the z component to set
  5564. * @param w defines the w component to set
  5565. * @returns the updated current matrix
  5566. */
  5567. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5568. if (index < 0 || index > 3) {
  5569. return this;
  5570. }
  5571. var i = index * 4;
  5572. this.m[i + 0] = x;
  5573. this.m[i + 1] = y;
  5574. this.m[i + 2] = z;
  5575. this.m[i + 3] = w;
  5576. this._markAsUpdated();
  5577. return this;
  5578. };
  5579. /**
  5580. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5581. * @param scale defines the scale factor
  5582. * @returns a new matrix
  5583. */
  5584. Matrix.prototype.scale = function (scale) {
  5585. var result = new Matrix();
  5586. this.scaleToRef(scale, result);
  5587. return result;
  5588. };
  5589. /**
  5590. * Scale the current matrix values by a factor to a given result matrix
  5591. * @param scale defines the scale factor
  5592. * @param result defines the matrix to store the result
  5593. * @returns the current matrix
  5594. */
  5595. Matrix.prototype.scaleToRef = function (scale, result) {
  5596. for (var index = 0; index < 16; index++) {
  5597. result.m[index] = this.m[index] * scale;
  5598. }
  5599. result._markAsUpdated();
  5600. return this;
  5601. };
  5602. /**
  5603. * Scale the current matrix values by a factor and add the result to a given matrix
  5604. * @param scale defines the scale factor
  5605. * @param result defines the Matrix to store the result
  5606. * @returns the current matrix
  5607. */
  5608. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5609. for (var index = 0; index < 16; index++) {
  5610. result.m[index] += this.m[index] * scale;
  5611. }
  5612. result._markAsUpdated();
  5613. return this;
  5614. };
  5615. /**
  5616. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5617. * @param ref matrix to store the result
  5618. */
  5619. Matrix.prototype.toNormalMatrix = function (ref) {
  5620. this.invertToRef(ref);
  5621. ref.transpose();
  5622. var m = ref.m;
  5623. 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);
  5624. };
  5625. /**
  5626. * Gets only rotation part of the current matrix
  5627. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5628. */
  5629. Matrix.prototype.getRotationMatrix = function () {
  5630. var result = Matrix.Identity();
  5631. this.getRotationMatrixToRef(result);
  5632. return result;
  5633. };
  5634. /**
  5635. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5636. * @param result defines the target matrix to store data to
  5637. * @returns the current matrix
  5638. */
  5639. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5640. var m = this.m;
  5641. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5642. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5643. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5644. if (this.determinant() <= 0) {
  5645. sy *= -1;
  5646. }
  5647. if (sx === 0 || sy === 0 || sz === 0) {
  5648. Matrix.IdentityToRef(result);
  5649. }
  5650. else {
  5651. 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);
  5652. }
  5653. return this;
  5654. };
  5655. // Statics
  5656. /**
  5657. * Creates a matrix from an array
  5658. * @param array defines the source array
  5659. * @param offset defines an offset in the source array
  5660. * @returns a new Matrix set from the starting index of the given array
  5661. */
  5662. Matrix.FromArray = function (array, offset) {
  5663. var result = new Matrix();
  5664. if (!offset) {
  5665. offset = 0;
  5666. }
  5667. Matrix.FromArrayToRef(array, offset, result);
  5668. return result;
  5669. };
  5670. /**
  5671. * Copy the content of an array into a given matrix
  5672. * @param array defines the source array
  5673. * @param offset defines an offset in the source array
  5674. * @param result defines the target matrix
  5675. */
  5676. Matrix.FromArrayToRef = function (array, offset, result) {
  5677. for (var index = 0; index < 16; index++) {
  5678. result.m[index] = array[index + offset];
  5679. }
  5680. result._markAsUpdated();
  5681. };
  5682. /**
  5683. * Stores an array into a matrix after having multiplied each component by a given factor
  5684. * @param array defines the source array
  5685. * @param offset defines the offset in the source array
  5686. * @param scale defines the scaling factor
  5687. * @param result defines the target matrix
  5688. */
  5689. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5690. for (var index = 0; index < 16; index++) {
  5691. result.m[index] = array[index + offset] * scale;
  5692. }
  5693. result._markAsUpdated();
  5694. };
  5695. /**
  5696. * Stores a list of values (16) inside a given matrix
  5697. * @param initialM11 defines 1st value of 1st row
  5698. * @param initialM12 defines 2nd value of 1st row
  5699. * @param initialM13 defines 3rd value of 1st row
  5700. * @param initialM14 defines 4th value of 1st row
  5701. * @param initialM21 defines 1st value of 2nd row
  5702. * @param initialM22 defines 2nd value of 2nd row
  5703. * @param initialM23 defines 3rd value of 2nd row
  5704. * @param initialM24 defines 4th value of 2nd row
  5705. * @param initialM31 defines 1st value of 3rd row
  5706. * @param initialM32 defines 2nd value of 3rd row
  5707. * @param initialM33 defines 3rd value of 3rd row
  5708. * @param initialM34 defines 4th value of 3rd row
  5709. * @param initialM41 defines 1st value of 4th row
  5710. * @param initialM42 defines 2nd value of 4th row
  5711. * @param initialM43 defines 3rd value of 4th row
  5712. * @param initialM44 defines 4th value of 4th row
  5713. * @param result defines the target matrix
  5714. */
  5715. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5716. result.m[0] = initialM11;
  5717. result.m[1] = initialM12;
  5718. result.m[2] = initialM13;
  5719. result.m[3] = initialM14;
  5720. result.m[4] = initialM21;
  5721. result.m[5] = initialM22;
  5722. result.m[6] = initialM23;
  5723. result.m[7] = initialM24;
  5724. result.m[8] = initialM31;
  5725. result.m[9] = initialM32;
  5726. result.m[10] = initialM33;
  5727. result.m[11] = initialM34;
  5728. result.m[12] = initialM41;
  5729. result.m[13] = initialM42;
  5730. result.m[14] = initialM43;
  5731. result.m[15] = initialM44;
  5732. result._markAsUpdated();
  5733. };
  5734. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5735. /**
  5736. * Gets an identity matrix that must not be updated
  5737. */
  5738. get: function () {
  5739. return Matrix._identityReadOnly;
  5740. },
  5741. enumerable: true,
  5742. configurable: true
  5743. });
  5744. /**
  5745. * Creates new matrix from a list of values (16)
  5746. * @param initialM11 defines 1st value of 1st row
  5747. * @param initialM12 defines 2nd value of 1st row
  5748. * @param initialM13 defines 3rd value of 1st row
  5749. * @param initialM14 defines 4th value of 1st row
  5750. * @param initialM21 defines 1st value of 2nd row
  5751. * @param initialM22 defines 2nd value of 2nd row
  5752. * @param initialM23 defines 3rd value of 2nd row
  5753. * @param initialM24 defines 4th value of 2nd row
  5754. * @param initialM31 defines 1st value of 3rd row
  5755. * @param initialM32 defines 2nd value of 3rd row
  5756. * @param initialM33 defines 3rd value of 3rd row
  5757. * @param initialM34 defines 4th value of 3rd row
  5758. * @param initialM41 defines 1st value of 4th row
  5759. * @param initialM42 defines 2nd value of 4th row
  5760. * @param initialM43 defines 3rd value of 4th row
  5761. * @param initialM44 defines 4th value of 4th row
  5762. * @returns the new matrix
  5763. */
  5764. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5765. var result = new Matrix();
  5766. result.m[0] = initialM11;
  5767. result.m[1] = initialM12;
  5768. result.m[2] = initialM13;
  5769. result.m[3] = initialM14;
  5770. result.m[4] = initialM21;
  5771. result.m[5] = initialM22;
  5772. result.m[6] = initialM23;
  5773. result.m[7] = initialM24;
  5774. result.m[8] = initialM31;
  5775. result.m[9] = initialM32;
  5776. result.m[10] = initialM33;
  5777. result.m[11] = initialM34;
  5778. result.m[12] = initialM41;
  5779. result.m[13] = initialM42;
  5780. result.m[14] = initialM43;
  5781. result.m[15] = initialM44;
  5782. return result;
  5783. };
  5784. /**
  5785. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5786. * @param scale defines the scale vector3
  5787. * @param rotation defines the rotation quaternion
  5788. * @param translation defines the translation vector3
  5789. * @returns a new matrix
  5790. */
  5791. Matrix.Compose = function (scale, rotation, translation) {
  5792. var result = Matrix.Identity();
  5793. Matrix.ComposeToRef(scale, rotation, translation, result);
  5794. return result;
  5795. };
  5796. /**
  5797. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5798. * @param scale defines the scale vector3
  5799. * @param rotation defines the rotation quaternion
  5800. * @param translation defines the translation vector3
  5801. * @param result defines the target matrix
  5802. */
  5803. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5804. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5805. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5806. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5807. result.setTranslation(translation);
  5808. };
  5809. /**
  5810. * Creates a new identity matrix
  5811. * @returns a new identity matrix
  5812. */
  5813. Matrix.Identity = function () {
  5814. 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);
  5815. };
  5816. /**
  5817. * Creates a new identity matrix and stores the result in a given matrix
  5818. * @param result defines the target matrix
  5819. */
  5820. Matrix.IdentityToRef = function (result) {
  5821. 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);
  5822. };
  5823. /**
  5824. * Creates a new zero matrix
  5825. * @returns a new zero matrix
  5826. */
  5827. Matrix.Zero = function () {
  5828. 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);
  5829. };
  5830. /**
  5831. * Creates a new rotation matrix for "angle" radians around the X axis
  5832. * @param angle defines the angle (in radians) to use
  5833. * @return the new matrix
  5834. */
  5835. Matrix.RotationX = function (angle) {
  5836. var result = new Matrix();
  5837. Matrix.RotationXToRef(angle, result);
  5838. return result;
  5839. };
  5840. /**
  5841. * Creates a new matrix as the invert of a given matrix
  5842. * @param source defines the source matrix
  5843. * @returns the new matrix
  5844. */
  5845. Matrix.Invert = function (source) {
  5846. var result = new Matrix();
  5847. source.invertToRef(result);
  5848. return result;
  5849. };
  5850. /**
  5851. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5852. * @param angle defines the angle (in radians) to use
  5853. * @param result defines the target matrix
  5854. */
  5855. Matrix.RotationXToRef = function (angle, result) {
  5856. var s = Math.sin(angle);
  5857. var c = Math.cos(angle);
  5858. result.m[0] = 1.0;
  5859. result.m[15] = 1.0;
  5860. result.m[5] = c;
  5861. result.m[10] = c;
  5862. result.m[9] = -s;
  5863. result.m[6] = s;
  5864. result.m[1] = 0.0;
  5865. result.m[2] = 0.0;
  5866. result.m[3] = 0.0;
  5867. result.m[4] = 0.0;
  5868. result.m[7] = 0.0;
  5869. result.m[8] = 0.0;
  5870. result.m[11] = 0.0;
  5871. result.m[12] = 0.0;
  5872. result.m[13] = 0.0;
  5873. result.m[14] = 0.0;
  5874. result._markAsUpdated();
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the Y axis
  5878. * @param angle defines the angle (in radians) to use
  5879. * @return the new matrix
  5880. */
  5881. Matrix.RotationY = function (angle) {
  5882. var result = new Matrix();
  5883. Matrix.RotationYToRef(angle, result);
  5884. return result;
  5885. };
  5886. /**
  5887. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5888. * @param angle defines the angle (in radians) to use
  5889. * @param result defines the target matrix
  5890. */
  5891. Matrix.RotationYToRef = function (angle, result) {
  5892. var s = Math.sin(angle);
  5893. var c = Math.cos(angle);
  5894. result.m[5] = 1.0;
  5895. result.m[15] = 1.0;
  5896. result.m[0] = c;
  5897. result.m[2] = -s;
  5898. result.m[8] = s;
  5899. result.m[10] = c;
  5900. result.m[1] = 0.0;
  5901. result.m[3] = 0.0;
  5902. result.m[4] = 0.0;
  5903. result.m[6] = 0.0;
  5904. result.m[7] = 0.0;
  5905. result.m[9] = 0.0;
  5906. result.m[11] = 0.0;
  5907. result.m[12] = 0.0;
  5908. result.m[13] = 0.0;
  5909. result.m[14] = 0.0;
  5910. result._markAsUpdated();
  5911. };
  5912. /**
  5913. * Creates a new rotation matrix for "angle" radians around the Z axis
  5914. * @param angle defines the angle (in radians) to use
  5915. * @return the new matrix
  5916. */
  5917. Matrix.RotationZ = function (angle) {
  5918. var result = new Matrix();
  5919. Matrix.RotationZToRef(angle, result);
  5920. return result;
  5921. };
  5922. /**
  5923. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5924. * @param angle defines the angle (in radians) to use
  5925. * @param result defines the target matrix
  5926. */
  5927. Matrix.RotationZToRef = function (angle, result) {
  5928. var s = Math.sin(angle);
  5929. var c = Math.cos(angle);
  5930. result.m[10] = 1.0;
  5931. result.m[15] = 1.0;
  5932. result.m[0] = c;
  5933. result.m[1] = s;
  5934. result.m[4] = -s;
  5935. result.m[5] = c;
  5936. result.m[2] = 0.0;
  5937. result.m[3] = 0.0;
  5938. result.m[6] = 0.0;
  5939. result.m[7] = 0.0;
  5940. result.m[8] = 0.0;
  5941. result.m[9] = 0.0;
  5942. result.m[11] = 0.0;
  5943. result.m[12] = 0.0;
  5944. result.m[13] = 0.0;
  5945. result.m[14] = 0.0;
  5946. result._markAsUpdated();
  5947. };
  5948. /**
  5949. * Creates a new rotation matrix for "angle" radians around the given axis
  5950. * @param axis defines the axis to use
  5951. * @param angle defines the angle (in radians) to use
  5952. * @return the new matrix
  5953. */
  5954. Matrix.RotationAxis = function (axis, angle) {
  5955. var result = Matrix.Zero();
  5956. Matrix.RotationAxisToRef(axis, angle, result);
  5957. return result;
  5958. };
  5959. /**
  5960. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5961. * @param axis defines the axis to use
  5962. * @param angle defines the angle (in radians) to use
  5963. * @param result defines the target matrix
  5964. */
  5965. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5966. var s = Math.sin(-angle);
  5967. var c = Math.cos(-angle);
  5968. var c1 = 1 - c;
  5969. axis.normalize();
  5970. result.m[0] = (axis.x * axis.x) * c1 + c;
  5971. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5972. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5973. result.m[3] = 0.0;
  5974. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5975. result.m[5] = (axis.y * axis.y) * c1 + c;
  5976. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5977. result.m[7] = 0.0;
  5978. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5979. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5980. result.m[10] = (axis.z * axis.z) * c1 + c;
  5981. result.m[11] = 0.0;
  5982. result.m[15] = 1.0;
  5983. result._markAsUpdated();
  5984. };
  5985. /**
  5986. * Creates a rotation matrix
  5987. * @param yaw defines the yaw angle in radians (Y axis)
  5988. * @param pitch defines the pitch angle in radians (X axis)
  5989. * @param roll defines the roll angle in radians (X axis)
  5990. * @returns the new rotation matrix
  5991. */
  5992. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5993. var result = new Matrix();
  5994. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Creates a rotation matrix and stores it in a given matrix
  5999. * @param yaw defines the yaw angle in radians (Y axis)
  6000. * @param pitch defines the pitch angle in radians (X axis)
  6001. * @param roll defines the roll angle in radians (X axis)
  6002. * @param result defines the target matrix
  6003. */
  6004. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6005. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6006. this._tempQuaternion.toRotationMatrix(result);
  6007. };
  6008. /**
  6009. * Creates a scaling matrix
  6010. * @param x defines the scale factor on X axis
  6011. * @param y defines the scale factor on Y axis
  6012. * @param z defines the scale factor on Z axis
  6013. * @returns the new matrix
  6014. */
  6015. Matrix.Scaling = function (x, y, z) {
  6016. var result = Matrix.Zero();
  6017. Matrix.ScalingToRef(x, y, z, result);
  6018. return result;
  6019. };
  6020. /**
  6021. * Creates a scaling matrix and stores it in a given matrix
  6022. * @param x defines the scale factor on X axis
  6023. * @param y defines the scale factor on Y axis
  6024. * @param z defines the scale factor on Z axis
  6025. * @param result defines the target matrix
  6026. */
  6027. Matrix.ScalingToRef = function (x, y, z, result) {
  6028. result.m[0] = x;
  6029. result.m[1] = 0.0;
  6030. result.m[2] = 0.0;
  6031. result.m[3] = 0.0;
  6032. result.m[4] = 0.0;
  6033. result.m[5] = y;
  6034. result.m[6] = 0.0;
  6035. result.m[7] = 0.0;
  6036. result.m[8] = 0.0;
  6037. result.m[9] = 0.0;
  6038. result.m[10] = z;
  6039. result.m[11] = 0.0;
  6040. result.m[12] = 0.0;
  6041. result.m[13] = 0.0;
  6042. result.m[14] = 0.0;
  6043. result.m[15] = 1.0;
  6044. result._markAsUpdated();
  6045. };
  6046. /**
  6047. * Creates a translation matrix
  6048. * @param x defines the translation on X axis
  6049. * @param y defines the translation on Y axis
  6050. * @param z defines the translationon Z axis
  6051. * @returns the new matrix
  6052. */
  6053. Matrix.Translation = function (x, y, z) {
  6054. var result = Matrix.Identity();
  6055. Matrix.TranslationToRef(x, y, z, result);
  6056. return result;
  6057. };
  6058. /**
  6059. * Creates a translation matrix and stores it in a given matrix
  6060. * @param x defines the translation on X axis
  6061. * @param y defines the translation on Y axis
  6062. * @param z defines the translationon Z axis
  6063. * @param result defines the target matrix
  6064. */
  6065. Matrix.TranslationToRef = function (x, y, z, result) {
  6066. 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);
  6067. };
  6068. /**
  6069. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6070. * @param startValue defines the start value
  6071. * @param endValue defines the end value
  6072. * @param gradient defines the gradient factor
  6073. * @returns the new matrix
  6074. */
  6075. Matrix.Lerp = function (startValue, endValue, gradient) {
  6076. var result = Matrix.Zero();
  6077. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6078. return result;
  6079. };
  6080. /**
  6081. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6082. * @param startValue defines the start value
  6083. * @param endValue defines the end value
  6084. * @param gradient defines the gradient factor
  6085. * @param result defines the Matrix object where to store data
  6086. */
  6087. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6088. for (var index = 0; index < 16; index++) {
  6089. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6090. }
  6091. result._markAsUpdated();
  6092. };
  6093. /**
  6094. * Builds a new matrix whose values are computed by:
  6095. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6096. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6097. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6098. * @param startValue defines the first matrix
  6099. * @param endValue defines the second matrix
  6100. * @param gradient defines the gradient between the two matrices
  6101. * @returns the new matrix
  6102. */
  6103. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6104. var result = Matrix.Zero();
  6105. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6106. return result;
  6107. };
  6108. /**
  6109. * Update a matrix to values which are computed by:
  6110. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6111. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6112. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6113. * @param startValue defines the first matrix
  6114. * @param endValue defines the second matrix
  6115. * @param gradient defines the gradient between the two matrices
  6116. * @param result defines the target matrix
  6117. */
  6118. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6119. var startScale = MathTmp.Vector3[0];
  6120. var startRotation = MathTmp.Quaternion[0];
  6121. var startTranslation = MathTmp.Vector3[1];
  6122. startValue.decompose(startScale, startRotation, startTranslation);
  6123. var endScale = MathTmp.Vector3[2];
  6124. var endRotation = MathTmp.Quaternion[1];
  6125. var endTranslation = MathTmp.Vector3[3];
  6126. endValue.decompose(endScale, endRotation, endTranslation);
  6127. var resultScale = MathTmp.Vector3[4];
  6128. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6129. var resultRotation = MathTmp.Quaternion[2];
  6130. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6131. var resultTranslation = MathTmp.Vector3[5];
  6132. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6133. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6134. };
  6135. /**
  6136. * 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"
  6137. * This function works in left handed mode
  6138. * @param eye defines the final position of the entity
  6139. * @param target defines where the entity should look at
  6140. * @param up defines the up vector for the entity
  6141. * @returns the new matrix
  6142. */
  6143. Matrix.LookAtLH = function (eye, target, up) {
  6144. var result = Matrix.Zero();
  6145. Matrix.LookAtLHToRef(eye, target, up, result);
  6146. return result;
  6147. };
  6148. /**
  6149. * 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".
  6150. * This function works in left handed mode
  6151. * @param eye defines the final position of the entity
  6152. * @param target defines where the entity should look at
  6153. * @param up defines the up vector for the entity
  6154. * @param result defines the target matrix
  6155. */
  6156. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6157. // Z axis
  6158. target.subtractToRef(eye, this._zAxis);
  6159. this._zAxis.normalize();
  6160. // X axis
  6161. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6162. if (this._xAxis.lengthSquared() === 0) {
  6163. this._xAxis.x = 1.0;
  6164. }
  6165. else {
  6166. this._xAxis.normalize();
  6167. }
  6168. // Y axis
  6169. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6170. this._yAxis.normalize();
  6171. // Eye angles
  6172. var ex = -Vector3.Dot(this._xAxis, eye);
  6173. var ey = -Vector3.Dot(this._yAxis, eye);
  6174. var ez = -Vector3.Dot(this._zAxis, eye);
  6175. 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);
  6176. };
  6177. /**
  6178. * 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"
  6179. * This function works in right handed mode
  6180. * @param eye defines the final position of the entity
  6181. * @param target defines where the entity should look at
  6182. * @param up defines the up vector for the entity
  6183. * @returns the new matrix
  6184. */
  6185. Matrix.LookAtRH = function (eye, target, up) {
  6186. var result = Matrix.Zero();
  6187. Matrix.LookAtRHToRef(eye, target, up, result);
  6188. return result;
  6189. };
  6190. /**
  6191. * 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".
  6192. * This function works in right handed mode
  6193. * @param eye defines the final position of the entity
  6194. * @param target defines where the entity should look at
  6195. * @param up defines the up vector for the entity
  6196. * @param result defines the target matrix
  6197. */
  6198. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6199. // Z axis
  6200. eye.subtractToRef(target, this._zAxis);
  6201. this._zAxis.normalize();
  6202. // X axis
  6203. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6204. if (this._xAxis.lengthSquared() === 0) {
  6205. this._xAxis.x = 1.0;
  6206. }
  6207. else {
  6208. this._xAxis.normalize();
  6209. }
  6210. // Y axis
  6211. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6212. this._yAxis.normalize();
  6213. // Eye angles
  6214. var ex = -Vector3.Dot(this._xAxis, eye);
  6215. var ey = -Vector3.Dot(this._yAxis, eye);
  6216. var ez = -Vector3.Dot(this._zAxis, eye);
  6217. 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);
  6218. };
  6219. /**
  6220. * Create a left-handed orthographic projection matrix
  6221. * @param width defines the viewport width
  6222. * @param height defines the viewport height
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @returns a new matrix as a left-handed orthographic projection matrix
  6226. */
  6227. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6228. var matrix = Matrix.Zero();
  6229. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6230. return matrix;
  6231. };
  6232. /**
  6233. * Store a left-handed orthographic projection to a given matrix
  6234. * @param width defines the viewport width
  6235. * @param height defines the viewport height
  6236. * @param znear defines the near clip plane
  6237. * @param zfar defines the far clip plane
  6238. * @param result defines the target matrix
  6239. */
  6240. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 / width;
  6244. var b = 2.0 / height;
  6245. var c = 2.0 / (f - n);
  6246. var d = -(f + n) / (f - n);
  6247. 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);
  6248. };
  6249. /**
  6250. * Create a left-handed orthographic projection matrix
  6251. * @param left defines the viewport left coordinate
  6252. * @param right defines the viewport right coordinate
  6253. * @param bottom defines the viewport bottom coordinate
  6254. * @param top defines the viewport top coordinate
  6255. * @param znear defines the near clip plane
  6256. * @param zfar defines the far clip plane
  6257. * @returns a new matrix as a left-handed orthographic projection matrix
  6258. */
  6259. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6260. var matrix = Matrix.Zero();
  6261. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6262. return matrix;
  6263. };
  6264. /**
  6265. * Stores a left-handed orthographic projection into a given matrix
  6266. * @param left defines the viewport left coordinate
  6267. * @param right defines the viewport right coordinate
  6268. * @param bottom defines the viewport bottom coordinate
  6269. * @param top defines the viewport top coordinate
  6270. * @param znear defines the near clip plane
  6271. * @param zfar defines the far clip plane
  6272. * @param result defines the target matrix
  6273. */
  6274. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6275. var n = znear;
  6276. var f = zfar;
  6277. var a = 2.0 / (right - left);
  6278. var b = 2.0 / (top - bottom);
  6279. var c = 2.0 / (f - n);
  6280. var d = -(f + n) / (f - n);
  6281. var i0 = (left + right) / (left - right);
  6282. var i1 = (top + bottom) / (bottom - top);
  6283. 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);
  6284. };
  6285. /**
  6286. * Creates a right-handed orthographic projection matrix
  6287. * @param left defines the viewport left coordinate
  6288. * @param right defines the viewport right coordinate
  6289. * @param bottom defines the viewport bottom coordinate
  6290. * @param top defines the viewport top coordinate
  6291. * @param znear defines the near clip plane
  6292. * @param zfar defines the far clip plane
  6293. * @returns a new matrix as a right-handed orthographic projection matrix
  6294. */
  6295. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6296. var matrix = Matrix.Zero();
  6297. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6298. return matrix;
  6299. };
  6300. /**
  6301. * Stores a right-handed orthographic projection into a given matrix
  6302. * @param left defines the viewport left coordinate
  6303. * @param right defines the viewport right coordinate
  6304. * @param bottom defines the viewport bottom coordinate
  6305. * @param top defines the viewport top coordinate
  6306. * @param znear defines the near clip plane
  6307. * @param zfar defines the far clip plane
  6308. * @param result defines the target matrix
  6309. */
  6310. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6311. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6312. result.m[10] *= -1.0;
  6313. };
  6314. /**
  6315. * Creates a left-handed perspective projection matrix
  6316. * @param width defines the viewport width
  6317. * @param height defines the viewport height
  6318. * @param znear defines the near clip plane
  6319. * @param zfar defines the far clip plane
  6320. * @returns a new matrix as a left-handed perspective projection matrix
  6321. */
  6322. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6323. var matrix = Matrix.Zero();
  6324. var n = znear;
  6325. var f = zfar;
  6326. var a = 2.0 * n / width;
  6327. var b = 2.0 * n / height;
  6328. var c = (f + n) / (f - n);
  6329. var d = -2.0 * f * n / (f - n);
  6330. 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);
  6331. return matrix;
  6332. };
  6333. /**
  6334. * Creates a left-handed perspective projection matrix
  6335. * @param fov defines the horizontal field of view
  6336. * @param aspect defines the aspect ratio
  6337. * @param znear defines the near clip plane
  6338. * @param zfar defines the far clip plane
  6339. * @returns a new matrix as a left-handed perspective projection matrix
  6340. */
  6341. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6342. var matrix = Matrix.Zero();
  6343. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6344. return matrix;
  6345. };
  6346. /**
  6347. * Stores a left-handed perspective projection into a given matrix
  6348. * @param fov defines the horizontal field of view
  6349. * @param aspect defines the aspect ratio
  6350. * @param znear defines the near clip plane
  6351. * @param zfar defines the far clip plane
  6352. * @param result defines the target matrix
  6353. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6354. */
  6355. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6356. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6357. var n = znear;
  6358. var f = zfar;
  6359. var t = 1.0 / (Math.tan(fov * 0.5));
  6360. var a = isVerticalFovFixed ? (t / aspect) : t;
  6361. var b = isVerticalFovFixed ? t : (t * aspect);
  6362. var c = (f + n) / (f - n);
  6363. var d = -2.0 * f * n / (f - n);
  6364. 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);
  6365. };
  6366. /**
  6367. * Creates a right-handed perspective projection matrix
  6368. * @param fov defines the horizontal field of view
  6369. * @param aspect defines the aspect ratio
  6370. * @param znear defines the near clip plane
  6371. * @param zfar defines the far clip plane
  6372. * @returns a new matrix as a right-handed perspective projection matrix
  6373. */
  6374. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6375. var matrix = Matrix.Zero();
  6376. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6377. return matrix;
  6378. };
  6379. /**
  6380. * Stores a right-handed perspective projection into a given matrix
  6381. * @param fov defines the horizontal field of view
  6382. * @param aspect defines the aspect ratio
  6383. * @param znear defines the near clip plane
  6384. * @param zfar defines the far clip plane
  6385. * @param result defines the target matrix
  6386. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6387. */
  6388. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6389. //alternatively this could be expressed as:
  6390. // m = PerspectiveFovLHToRef
  6391. // m[10] *= -1.0;
  6392. // m[11] *= -1.0;
  6393. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6394. var n = znear;
  6395. var f = zfar;
  6396. var t = 1.0 / (Math.tan(fov * 0.5));
  6397. var a = isVerticalFovFixed ? (t / aspect) : t;
  6398. var b = isVerticalFovFixed ? t : (t * aspect);
  6399. var c = -(f + n) / (f - n);
  6400. var d = -2 * f * n / (f - n);
  6401. 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);
  6402. };
  6403. /**
  6404. * Stores a perspective projection for WebVR info a given matrix
  6405. * @param fov defines the field of view
  6406. * @param znear defines the near clip plane
  6407. * @param zfar defines the far clip plane
  6408. * @param result defines the target matrix
  6409. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6410. */
  6411. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6412. if (rightHanded === void 0) { rightHanded = false; }
  6413. var rightHandedFactor = rightHanded ? -1 : 1;
  6414. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6415. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6416. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6417. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6418. var xScale = 2.0 / (leftTan + rightTan);
  6419. var yScale = 2.0 / (upTan + downTan);
  6420. result.m[0] = xScale;
  6421. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6422. result.m[5] = yScale;
  6423. result.m[6] = result.m[7] = 0.0;
  6424. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6425. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6426. result.m[10] = -zfar / (znear - zfar);
  6427. result.m[11] = 1.0 * rightHandedFactor;
  6428. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6429. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6430. result._markAsUpdated();
  6431. };
  6432. /**
  6433. * Computes a complete transformation matrix
  6434. * @param viewport defines the viewport to use
  6435. * @param world defines the world matrix
  6436. * @param view defines the view matrix
  6437. * @param projection defines the projection matrix
  6438. * @param zmin defines the near clip plane
  6439. * @param zmax defines the far clip plane
  6440. * @returns the transformation matrix
  6441. */
  6442. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6443. var cw = viewport.width;
  6444. var ch = viewport.height;
  6445. var cx = viewport.x;
  6446. var cy = viewport.y;
  6447. 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);
  6448. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6449. };
  6450. /**
  6451. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6452. * @param matrix defines the matrix to use
  6453. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6454. */
  6455. Matrix.GetAsMatrix2x2 = function (matrix) {
  6456. return new Float32Array([
  6457. matrix.m[0], matrix.m[1],
  6458. matrix.m[4], matrix.m[5]
  6459. ]);
  6460. };
  6461. /**
  6462. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6463. * @param matrix defines the matrix to use
  6464. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6465. */
  6466. Matrix.GetAsMatrix3x3 = function (matrix) {
  6467. return new Float32Array([
  6468. matrix.m[0], matrix.m[1], matrix.m[2],
  6469. matrix.m[4], matrix.m[5], matrix.m[6],
  6470. matrix.m[8], matrix.m[9], matrix.m[10]
  6471. ]);
  6472. };
  6473. /**
  6474. * Compute the transpose of a given matrix
  6475. * @param matrix defines the matrix to transpose
  6476. * @returns the new matrix
  6477. */
  6478. Matrix.Transpose = function (matrix) {
  6479. var result = new Matrix();
  6480. Matrix.TransposeToRef(matrix, result);
  6481. return result;
  6482. };
  6483. /**
  6484. * Compute the transpose of a matrix and store it in a target matrix
  6485. * @param matrix defines the matrix to transpose
  6486. * @param result defines the target matrix
  6487. */
  6488. Matrix.TransposeToRef = function (matrix, result) {
  6489. result.m[0] = matrix.m[0];
  6490. result.m[1] = matrix.m[4];
  6491. result.m[2] = matrix.m[8];
  6492. result.m[3] = matrix.m[12];
  6493. result.m[4] = matrix.m[1];
  6494. result.m[5] = matrix.m[5];
  6495. result.m[6] = matrix.m[9];
  6496. result.m[7] = matrix.m[13];
  6497. result.m[8] = matrix.m[2];
  6498. result.m[9] = matrix.m[6];
  6499. result.m[10] = matrix.m[10];
  6500. result.m[11] = matrix.m[14];
  6501. result.m[12] = matrix.m[3];
  6502. result.m[13] = matrix.m[7];
  6503. result.m[14] = matrix.m[11];
  6504. result.m[15] = matrix.m[15];
  6505. };
  6506. /**
  6507. * Computes a reflection matrix from a plane
  6508. * @param plane defines the reflection plane
  6509. * @returns a new matrix
  6510. */
  6511. Matrix.Reflection = function (plane) {
  6512. var matrix = new Matrix();
  6513. Matrix.ReflectionToRef(plane, matrix);
  6514. return matrix;
  6515. };
  6516. /**
  6517. * Computes a reflection matrix from a plane
  6518. * @param plane defines the reflection plane
  6519. * @param result defines the target matrix
  6520. */
  6521. Matrix.ReflectionToRef = function (plane, result) {
  6522. plane.normalize();
  6523. var x = plane.normal.x;
  6524. var y = plane.normal.y;
  6525. var z = plane.normal.z;
  6526. var temp = -2 * x;
  6527. var temp2 = -2 * y;
  6528. var temp3 = -2 * z;
  6529. result.m[0] = (temp * x) + 1;
  6530. result.m[1] = temp2 * x;
  6531. result.m[2] = temp3 * x;
  6532. result.m[3] = 0.0;
  6533. result.m[4] = temp * y;
  6534. result.m[5] = (temp2 * y) + 1;
  6535. result.m[6] = temp3 * y;
  6536. result.m[7] = 0.0;
  6537. result.m[8] = temp * z;
  6538. result.m[9] = temp2 * z;
  6539. result.m[10] = (temp3 * z) + 1;
  6540. result.m[11] = 0.0;
  6541. result.m[12] = temp * plane.d;
  6542. result.m[13] = temp2 * plane.d;
  6543. result.m[14] = temp3 * plane.d;
  6544. result.m[15] = 1.0;
  6545. result._markAsUpdated();
  6546. };
  6547. /**
  6548. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6549. * @param xaxis defines the value of the 1st axis
  6550. * @param yaxis defines the value of the 2nd axis
  6551. * @param zaxis defines the value of the 3rd axis
  6552. * @param result defines the target matrix
  6553. */
  6554. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6555. result.m[0] = xaxis.x;
  6556. result.m[1] = xaxis.y;
  6557. result.m[2] = xaxis.z;
  6558. result.m[3] = 0.0;
  6559. result.m[4] = yaxis.x;
  6560. result.m[5] = yaxis.y;
  6561. result.m[6] = yaxis.z;
  6562. result.m[7] = 0.0;
  6563. result.m[8] = zaxis.x;
  6564. result.m[9] = zaxis.y;
  6565. result.m[10] = zaxis.z;
  6566. result.m[11] = 0.0;
  6567. result.m[12] = 0.0;
  6568. result.m[13] = 0.0;
  6569. result.m[14] = 0.0;
  6570. result.m[15] = 1.0;
  6571. result._markAsUpdated();
  6572. };
  6573. /**
  6574. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6575. * @param quat defines the quaternion to use
  6576. * @param result defines the target matrix
  6577. */
  6578. Matrix.FromQuaternionToRef = function (quat, result) {
  6579. var xx = quat.x * quat.x;
  6580. var yy = quat.y * quat.y;
  6581. var zz = quat.z * quat.z;
  6582. var xy = quat.x * quat.y;
  6583. var zw = quat.z * quat.w;
  6584. var zx = quat.z * quat.x;
  6585. var yw = quat.y * quat.w;
  6586. var yz = quat.y * quat.z;
  6587. var xw = quat.x * quat.w;
  6588. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6589. result.m[1] = 2.0 * (xy + zw);
  6590. result.m[2] = 2.0 * (zx - yw);
  6591. result.m[3] = 0.0;
  6592. result.m[4] = 2.0 * (xy - zw);
  6593. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6594. result.m[6] = 2.0 * (yz + xw);
  6595. result.m[7] = 0.0;
  6596. result.m[8] = 2.0 * (zx + yw);
  6597. result.m[9] = 2.0 * (yz - xw);
  6598. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6599. result.m[11] = 0.0;
  6600. result.m[12] = 0.0;
  6601. result.m[13] = 0.0;
  6602. result.m[14] = 0.0;
  6603. result.m[15] = 1.0;
  6604. result._markAsUpdated();
  6605. };
  6606. Matrix._tempQuaternion = new Quaternion();
  6607. Matrix._xAxis = Vector3.Zero();
  6608. Matrix._yAxis = Vector3.Zero();
  6609. Matrix._zAxis = Vector3.Zero();
  6610. Matrix._updateFlagSeed = 0;
  6611. Matrix._identityReadOnly = Matrix.Identity();
  6612. return Matrix;
  6613. }());
  6614. BABYLON.Matrix = Matrix;
  6615. var Plane = /** @class */ (function () {
  6616. /**
  6617. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6618. */
  6619. function Plane(a, b, c, d) {
  6620. this.normal = new Vector3(a, b, c);
  6621. this.d = d;
  6622. }
  6623. /**
  6624. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6625. */
  6626. Plane.prototype.asArray = function () {
  6627. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6628. };
  6629. // Methods
  6630. /**
  6631. * Returns a new plane copied from the current Plane.
  6632. */
  6633. Plane.prototype.clone = function () {
  6634. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6635. };
  6636. /**
  6637. * Returns the string "Plane".
  6638. */
  6639. Plane.prototype.getClassName = function () {
  6640. return "Plane";
  6641. };
  6642. /**
  6643. * Returns the Plane hash code.
  6644. */
  6645. Plane.prototype.getHashCode = function () {
  6646. var hash = this.normal.getHashCode();
  6647. hash = (hash * 397) ^ (this.d || 0);
  6648. return hash;
  6649. };
  6650. /**
  6651. * Normalize the current Plane in place.
  6652. * Returns the updated Plane.
  6653. */
  6654. Plane.prototype.normalize = function () {
  6655. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6656. var magnitude = 0.0;
  6657. if (norm !== 0) {
  6658. magnitude = 1.0 / norm;
  6659. }
  6660. this.normal.x *= magnitude;
  6661. this.normal.y *= magnitude;
  6662. this.normal.z *= magnitude;
  6663. this.d *= magnitude;
  6664. return this;
  6665. };
  6666. /**
  6667. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6668. */
  6669. Plane.prototype.transform = function (transformation) {
  6670. var transposedMatrix = Matrix.Transpose(transformation);
  6671. var x = this.normal.x;
  6672. var y = this.normal.y;
  6673. var z = this.normal.z;
  6674. var d = this.d;
  6675. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6676. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6677. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6678. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6679. return new Plane(normalX, normalY, normalZ, finalD);
  6680. };
  6681. /**
  6682. * Returns the dot product (float) of the point coordinates and the plane normal.
  6683. */
  6684. Plane.prototype.dotCoordinate = function (point) {
  6685. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6686. };
  6687. /**
  6688. * Updates the current Plane from the plane defined by the three given points.
  6689. * Returns the updated Plane.
  6690. */
  6691. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6692. var x1 = point2.x - point1.x;
  6693. var y1 = point2.y - point1.y;
  6694. var z1 = point2.z - point1.z;
  6695. var x2 = point3.x - point1.x;
  6696. var y2 = point3.y - point1.y;
  6697. var z2 = point3.z - point1.z;
  6698. var yz = (y1 * z2) - (z1 * y2);
  6699. var xz = (z1 * x2) - (x1 * z2);
  6700. var xy = (x1 * y2) - (y1 * x2);
  6701. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6702. var invPyth;
  6703. if (pyth !== 0) {
  6704. invPyth = 1.0 / pyth;
  6705. }
  6706. else {
  6707. invPyth = 0.0;
  6708. }
  6709. this.normal.x = yz * invPyth;
  6710. this.normal.y = xz * invPyth;
  6711. this.normal.z = xy * invPyth;
  6712. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6713. return this;
  6714. };
  6715. /**
  6716. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6717. */
  6718. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6719. var dot = Vector3.Dot(this.normal, direction);
  6720. return (dot <= epsilon);
  6721. };
  6722. /**
  6723. * Returns the signed distance (float) from the given point to the Plane.
  6724. */
  6725. Plane.prototype.signedDistanceTo = function (point) {
  6726. return Vector3.Dot(point, this.normal) + this.d;
  6727. };
  6728. // Statics
  6729. /**
  6730. * Returns a new Plane from the given array.
  6731. */
  6732. Plane.FromArray = function (array) {
  6733. return new Plane(array[0], array[1], array[2], array[3]);
  6734. };
  6735. /**
  6736. * Returns a new Plane defined by the three given points.
  6737. */
  6738. Plane.FromPoints = function (point1, point2, point3) {
  6739. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6740. result.copyFromPoints(point1, point2, point3);
  6741. return result;
  6742. };
  6743. /**
  6744. * Returns a new Plane the normal vector to this plane at the given origin point.
  6745. * Note : the vector "normal" is updated because normalized.
  6746. */
  6747. Plane.FromPositionAndNormal = function (origin, normal) {
  6748. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6749. normal.normalize();
  6750. result.normal = normal;
  6751. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6752. return result;
  6753. };
  6754. /**
  6755. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6756. */
  6757. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6758. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6759. return Vector3.Dot(point, normal) + d;
  6760. };
  6761. return Plane;
  6762. }());
  6763. BABYLON.Plane = Plane;
  6764. var Viewport = /** @class */ (function () {
  6765. /**
  6766. * Creates a Viewport object located at (x, y) and sized (width, height).
  6767. */
  6768. function Viewport(x, y, width, height) {
  6769. this.x = x;
  6770. this.y = y;
  6771. this.width = width;
  6772. this.height = height;
  6773. }
  6774. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6775. if (renderWidthOrEngine.getRenderWidth) {
  6776. var engine = renderWidthOrEngine;
  6777. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6778. }
  6779. var renderWidth = renderWidthOrEngine;
  6780. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6781. };
  6782. /**
  6783. * Returns a new Viewport copied from the current one.
  6784. */
  6785. Viewport.prototype.clone = function () {
  6786. return new Viewport(this.x, this.y, this.width, this.height);
  6787. };
  6788. return Viewport;
  6789. }());
  6790. BABYLON.Viewport = Viewport;
  6791. var Frustum = /** @class */ (function () {
  6792. function Frustum() {
  6793. }
  6794. /**
  6795. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6796. */
  6797. Frustum.GetPlanes = function (transform) {
  6798. var frustumPlanes = [];
  6799. for (var index = 0; index < 6; index++) {
  6800. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6801. }
  6802. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6803. return frustumPlanes;
  6804. };
  6805. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6806. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6807. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6808. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6809. frustumPlane.d = transform.m[15] + transform.m[14];
  6810. frustumPlane.normalize();
  6811. };
  6812. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6813. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6814. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6815. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6816. frustumPlane.d = transform.m[15] - transform.m[14];
  6817. frustumPlane.normalize();
  6818. };
  6819. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6820. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6821. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6822. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6823. frustumPlane.d = transform.m[15] + transform.m[12];
  6824. frustumPlane.normalize();
  6825. };
  6826. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6827. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6828. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6829. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6830. frustumPlane.d = transform.m[15] - transform.m[12];
  6831. frustumPlane.normalize();
  6832. };
  6833. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6834. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6835. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6836. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6837. frustumPlane.d = transform.m[15] - transform.m[13];
  6838. frustumPlane.normalize();
  6839. };
  6840. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6841. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6842. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6843. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6844. frustumPlane.d = transform.m[15] + transform.m[13];
  6845. frustumPlane.normalize();
  6846. };
  6847. /**
  6848. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6849. */
  6850. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6851. // Near
  6852. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6853. // Far
  6854. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6855. // Left
  6856. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6857. // Right
  6858. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6859. // Top
  6860. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6861. // Bottom
  6862. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6863. };
  6864. return Frustum;
  6865. }());
  6866. BABYLON.Frustum = Frustum;
  6867. /** Defines supported spaces */
  6868. var Space;
  6869. (function (Space) {
  6870. /** Local (object) space */
  6871. Space[Space["LOCAL"] = 0] = "LOCAL";
  6872. /** World space */
  6873. Space[Space["WORLD"] = 1] = "WORLD";
  6874. /** Bone space */
  6875. Space[Space["BONE"] = 2] = "BONE";
  6876. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6877. /** Defines the 3 main axes */
  6878. var Axis = /** @class */ (function () {
  6879. function Axis() {
  6880. }
  6881. /** X axis */
  6882. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6883. /** Y axis */
  6884. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6885. /** Z axis */
  6886. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6887. return Axis;
  6888. }());
  6889. BABYLON.Axis = Axis;
  6890. ;
  6891. var BezierCurve = /** @class */ (function () {
  6892. function BezierCurve() {
  6893. }
  6894. /**
  6895. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6896. */
  6897. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6898. // Extract X (which is equal to time here)
  6899. var f0 = 1 - 3 * x2 + 3 * x1;
  6900. var f1 = 3 * x2 - 6 * x1;
  6901. var f2 = 3 * x1;
  6902. var refinedT = t;
  6903. for (var i = 0; i < 5; i++) {
  6904. var refinedT2 = refinedT * refinedT;
  6905. var refinedT3 = refinedT2 * refinedT;
  6906. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6907. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6908. refinedT -= (x - t) * slope;
  6909. refinedT = Math.min(1, Math.max(0, refinedT));
  6910. }
  6911. // Resolve cubic bezier for the given x
  6912. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6913. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6914. Math.pow(refinedT, 3);
  6915. };
  6916. return BezierCurve;
  6917. }());
  6918. BABYLON.BezierCurve = BezierCurve;
  6919. /**
  6920. * Defines potential orientation for back face culling
  6921. */
  6922. var Orientation;
  6923. (function (Orientation) {
  6924. /**
  6925. * Clockwise
  6926. */
  6927. Orientation[Orientation["CW"] = 0] = "CW";
  6928. /** Counter clockwise */
  6929. Orientation[Orientation["CCW"] = 1] = "CCW";
  6930. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6931. /**
  6932. * Defines angle representation
  6933. */
  6934. var Angle = /** @class */ (function () {
  6935. /**
  6936. * Creates an Angle object of "radians" radians (float).
  6937. */
  6938. function Angle(radians) {
  6939. this._radians = radians;
  6940. if (this._radians < 0.0)
  6941. this._radians += (2.0 * Math.PI);
  6942. }
  6943. /**
  6944. * Get value in degrees
  6945. * @returns the Angle value in degrees (float)
  6946. */
  6947. Angle.prototype.degrees = function () {
  6948. return this._radians * 180.0 / Math.PI;
  6949. };
  6950. /**
  6951. * Get value in radians
  6952. * @returns the Angle value in radians (float)
  6953. */
  6954. Angle.prototype.radians = function () {
  6955. return this._radians;
  6956. };
  6957. /**
  6958. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6959. * @param a defines first vector
  6960. * @param b defines second vector
  6961. * @returns a new Angle
  6962. */
  6963. Angle.BetweenTwoPoints = function (a, b) {
  6964. var delta = b.subtract(a);
  6965. var theta = Math.atan2(delta.y, delta.x);
  6966. return new Angle(theta);
  6967. };
  6968. /**
  6969. * Gets a new Angle object from the given float in radians
  6970. * @param radians defines the angle value in radians
  6971. * @returns a new Angle
  6972. */
  6973. Angle.FromRadians = function (radians) {
  6974. return new Angle(radians);
  6975. };
  6976. /**
  6977. * Gets a new Angle object from the given float in degrees
  6978. * @param degrees defines the angle value in degrees
  6979. * @returns a new Angle
  6980. */
  6981. Angle.FromDegrees = function (degrees) {
  6982. return new Angle(degrees * Math.PI / 180.0);
  6983. };
  6984. return Angle;
  6985. }());
  6986. BABYLON.Angle = Angle;
  6987. var Arc2 = /** @class */ (function () {
  6988. /**
  6989. * Creates an Arc object from the three given points : start, middle and end.
  6990. */
  6991. function Arc2(startPoint, midPoint, endPoint) {
  6992. this.startPoint = startPoint;
  6993. this.midPoint = midPoint;
  6994. this.endPoint = endPoint;
  6995. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6996. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6997. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6998. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6999. 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);
  7000. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7001. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7002. var a1 = this.startAngle.degrees();
  7003. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7004. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7005. // angles correction
  7006. if (a2 - a1 > +180.0)
  7007. a2 -= 360.0;
  7008. if (a2 - a1 < -180.0)
  7009. a2 += 360.0;
  7010. if (a3 - a2 > +180.0)
  7011. a3 -= 360.0;
  7012. if (a3 - a2 < -180.0)
  7013. a3 += 360.0;
  7014. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7015. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7016. }
  7017. return Arc2;
  7018. }());
  7019. BABYLON.Arc2 = Arc2;
  7020. var Path2 = /** @class */ (function () {
  7021. /**
  7022. * Creates a Path2 object from the starting 2D coordinates x and y.
  7023. */
  7024. function Path2(x, y) {
  7025. this._points = new Array();
  7026. this._length = 0.0;
  7027. this.closed = false;
  7028. this._points.push(new Vector2(x, y));
  7029. }
  7030. /**
  7031. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7032. * Returns the updated Path2.
  7033. */
  7034. Path2.prototype.addLineTo = function (x, y) {
  7035. if (this.closed) {
  7036. return this;
  7037. }
  7038. var newPoint = new Vector2(x, y);
  7039. var previousPoint = this._points[this._points.length - 1];
  7040. this._points.push(newPoint);
  7041. this._length += newPoint.subtract(previousPoint).length();
  7042. return this;
  7043. };
  7044. /**
  7045. * 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.
  7046. * Returns the updated Path2.
  7047. */
  7048. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7049. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7050. if (this.closed) {
  7051. return this;
  7052. }
  7053. var startPoint = this._points[this._points.length - 1];
  7054. var midPoint = new Vector2(midX, midY);
  7055. var endPoint = new Vector2(endX, endY);
  7056. var arc = new Arc2(startPoint, midPoint, endPoint);
  7057. var increment = arc.angle.radians() / numberOfSegments;
  7058. if (arc.orientation === Orientation.CW)
  7059. increment *= -1;
  7060. var currentAngle = arc.startAngle.radians() + increment;
  7061. for (var i = 0; i < numberOfSegments; i++) {
  7062. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7063. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7064. this.addLineTo(x, y);
  7065. currentAngle += increment;
  7066. }
  7067. return this;
  7068. };
  7069. /**
  7070. * Closes the Path2.
  7071. * Returns the Path2.
  7072. */
  7073. Path2.prototype.close = function () {
  7074. this.closed = true;
  7075. return this;
  7076. };
  7077. /**
  7078. * Returns the Path2 total length (float).
  7079. */
  7080. Path2.prototype.length = function () {
  7081. var result = this._length;
  7082. if (!this.closed) {
  7083. var lastPoint = this._points[this._points.length - 1];
  7084. var firstPoint = this._points[0];
  7085. result += (firstPoint.subtract(lastPoint).length());
  7086. }
  7087. return result;
  7088. };
  7089. /**
  7090. * Returns the Path2 internal array of points.
  7091. */
  7092. Path2.prototype.getPoints = function () {
  7093. return this._points;
  7094. };
  7095. /**
  7096. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7097. */
  7098. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7099. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7100. return Vector2.Zero();
  7101. }
  7102. var lengthPosition = normalizedLengthPosition * this.length();
  7103. var previousOffset = 0;
  7104. for (var i = 0; i < this._points.length; i++) {
  7105. var j = (i + 1) % this._points.length;
  7106. var a = this._points[i];
  7107. var b = this._points[j];
  7108. var bToA = b.subtract(a);
  7109. var nextOffset = (bToA.length() + previousOffset);
  7110. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7111. var dir = bToA.normalize();
  7112. var localOffset = lengthPosition - previousOffset;
  7113. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7114. }
  7115. previousOffset = nextOffset;
  7116. }
  7117. return Vector2.Zero();
  7118. };
  7119. /**
  7120. * Returns a new Path2 starting at the coordinates (x, y).
  7121. */
  7122. Path2.StartingAt = function (x, y) {
  7123. return new Path2(x, y);
  7124. };
  7125. return Path2;
  7126. }());
  7127. BABYLON.Path2 = Path2;
  7128. var Path3D = /** @class */ (function () {
  7129. /**
  7130. * new Path3D(path, normal, raw)
  7131. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7132. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7133. * path : an array of Vector3, the curve axis of the Path3D
  7134. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7135. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7136. */
  7137. function Path3D(path, firstNormal, raw) {
  7138. if (firstNormal === void 0) { firstNormal = null; }
  7139. this.path = path;
  7140. this._curve = new Array();
  7141. this._distances = new Array();
  7142. this._tangents = new Array();
  7143. this._normals = new Array();
  7144. this._binormals = new Array();
  7145. for (var p = 0; p < path.length; p++) {
  7146. this._curve[p] = path[p].clone(); // hard copy
  7147. }
  7148. this._raw = raw || false;
  7149. this._compute(firstNormal);
  7150. }
  7151. /**
  7152. * Returns the Path3D array of successive Vector3 designing its curve.
  7153. */
  7154. Path3D.prototype.getCurve = function () {
  7155. return this._curve;
  7156. };
  7157. /**
  7158. * Returns an array populated with tangent vectors on each Path3D curve point.
  7159. */
  7160. Path3D.prototype.getTangents = function () {
  7161. return this._tangents;
  7162. };
  7163. /**
  7164. * Returns an array populated with normal vectors on each Path3D curve point.
  7165. */
  7166. Path3D.prototype.getNormals = function () {
  7167. return this._normals;
  7168. };
  7169. /**
  7170. * Returns an array populated with binormal vectors on each Path3D curve point.
  7171. */
  7172. Path3D.prototype.getBinormals = function () {
  7173. return this._binormals;
  7174. };
  7175. /**
  7176. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7177. */
  7178. Path3D.prototype.getDistances = function () {
  7179. return this._distances;
  7180. };
  7181. /**
  7182. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7183. * Returns the same object updated.
  7184. */
  7185. Path3D.prototype.update = function (path, firstNormal) {
  7186. if (firstNormal === void 0) { firstNormal = null; }
  7187. for (var p = 0; p < path.length; p++) {
  7188. this._curve[p].x = path[p].x;
  7189. this._curve[p].y = path[p].y;
  7190. this._curve[p].z = path[p].z;
  7191. }
  7192. this._compute(firstNormal);
  7193. return this;
  7194. };
  7195. // private function compute() : computes tangents, normals and binormals
  7196. Path3D.prototype._compute = function (firstNormal) {
  7197. var l = this._curve.length;
  7198. // first and last tangents
  7199. this._tangents[0] = this._getFirstNonNullVector(0);
  7200. if (!this._raw) {
  7201. this._tangents[0].normalize();
  7202. }
  7203. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7204. if (!this._raw) {
  7205. this._tangents[l - 1].normalize();
  7206. }
  7207. // normals and binormals at first point : arbitrary vector with _normalVector()
  7208. var tg0 = this._tangents[0];
  7209. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7210. this._normals[0] = pp0;
  7211. if (!this._raw) {
  7212. this._normals[0].normalize();
  7213. }
  7214. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7215. if (!this._raw) {
  7216. this._binormals[0].normalize();
  7217. }
  7218. this._distances[0] = 0.0;
  7219. // normals and binormals : next points
  7220. var prev; // previous vector (segment)
  7221. var cur; // current vector (segment)
  7222. var curTang; // current tangent
  7223. // previous normal
  7224. var prevBinor; // previous binormal
  7225. for (var i = 1; i < l; i++) {
  7226. // tangents
  7227. prev = this._getLastNonNullVector(i);
  7228. if (i < l - 1) {
  7229. cur = this._getFirstNonNullVector(i);
  7230. this._tangents[i] = prev.add(cur);
  7231. this._tangents[i].normalize();
  7232. }
  7233. this._distances[i] = this._distances[i - 1] + prev.length();
  7234. // normals and binormals
  7235. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7236. curTang = this._tangents[i];
  7237. prevBinor = this._binormals[i - 1];
  7238. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7239. if (!this._raw) {
  7240. this._normals[i].normalize();
  7241. }
  7242. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7243. if (!this._raw) {
  7244. this._binormals[i].normalize();
  7245. }
  7246. }
  7247. };
  7248. // private function getFirstNonNullVector(index)
  7249. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7250. Path3D.prototype._getFirstNonNullVector = function (index) {
  7251. var i = 1;
  7252. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7253. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7254. i++;
  7255. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7256. }
  7257. return nNVector;
  7258. };
  7259. // private function getLastNonNullVector(index)
  7260. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7261. Path3D.prototype._getLastNonNullVector = function (index) {
  7262. var i = 1;
  7263. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7264. while (nLVector.length() === 0 && index > i + 1) {
  7265. i++;
  7266. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7267. }
  7268. return nLVector;
  7269. };
  7270. // private function normalVector(v0, vt, va) :
  7271. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7272. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7273. Path3D.prototype._normalVector = function (v0, vt, va) {
  7274. var normal0;
  7275. var tgl = vt.length();
  7276. if (tgl === 0.0) {
  7277. tgl = 1.0;
  7278. }
  7279. if (va === undefined || va === null) {
  7280. var point;
  7281. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7282. point = new Vector3(0.0, -1.0, 0.0);
  7283. }
  7284. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7285. point = new Vector3(1.0, 0.0, 0.0);
  7286. }
  7287. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7288. point = new Vector3(0.0, 0.0, 1.0);
  7289. }
  7290. else {
  7291. point = Vector3.Zero();
  7292. }
  7293. normal0 = Vector3.Cross(vt, point);
  7294. }
  7295. else {
  7296. normal0 = Vector3.Cross(vt, va);
  7297. Vector3.CrossToRef(normal0, vt, normal0);
  7298. }
  7299. normal0.normalize();
  7300. return normal0;
  7301. };
  7302. return Path3D;
  7303. }());
  7304. BABYLON.Path3D = Path3D;
  7305. var Curve3 = /** @class */ (function () {
  7306. /**
  7307. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7308. * A Curve3 is designed from a series of successive Vector3.
  7309. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7310. */
  7311. function Curve3(points) {
  7312. this._length = 0.0;
  7313. this._points = points;
  7314. this._length = this._computeLength(points);
  7315. }
  7316. /**
  7317. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7318. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7319. * @param v1 (Vector3) the control point
  7320. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7321. * @param nbPoints (integer) the wanted number of points in the curve
  7322. */
  7323. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7324. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7325. var bez = new Array();
  7326. var equation = function (t, val0, val1, val2) {
  7327. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7328. return res;
  7329. };
  7330. for (var i = 0; i <= nbPoints; i++) {
  7331. 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)));
  7332. }
  7333. return new Curve3(bez);
  7334. };
  7335. /**
  7336. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7337. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7338. * @param v1 (Vector3) the first control point
  7339. * @param v2 (Vector3) the second control point
  7340. * @param v3 (Vector3) the end point of the Cubic Bezier
  7341. * @param nbPoints (integer) the wanted number of points in the curve
  7342. */
  7343. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7344. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7345. var bez = new Array();
  7346. var equation = function (t, val0, val1, val2, val3) {
  7347. 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;
  7348. return res;
  7349. };
  7350. for (var i = 0; i <= nbPoints; i++) {
  7351. 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)));
  7352. }
  7353. return new Curve3(bez);
  7354. };
  7355. /**
  7356. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7357. * @param p1 (Vector3) the origin point of the Hermite Spline
  7358. * @param t1 (Vector3) the tangent vector at the origin point
  7359. * @param p2 (Vector3) the end point of the Hermite Spline
  7360. * @param t2 (Vector3) the tangent vector at the end point
  7361. * @param nbPoints (integer) the wanted number of points in the curve
  7362. */
  7363. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7364. var hermite = new Array();
  7365. var step = 1.0 / nbPoints;
  7366. for (var i = 0; i <= nbPoints; i++) {
  7367. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7368. }
  7369. return new Curve3(hermite);
  7370. };
  7371. /**
  7372. * Returns a Curve3 object along a CatmullRom Spline curve :
  7373. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7374. * @param nbPoints (integer) the wanted number of points between each curve control points
  7375. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7376. */
  7377. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7378. var catmullRom = new Array();
  7379. var step = 1.0 / nbPoints;
  7380. var amount = 0.0;
  7381. if (closed) {
  7382. var pointsCount = points.length;
  7383. for (var i = 0; i < pointsCount; i++) {
  7384. amount = 0;
  7385. for (var c = 0; c < nbPoints; c++) {
  7386. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7387. amount += step;
  7388. }
  7389. }
  7390. catmullRom.push(catmullRom[0]);
  7391. }
  7392. else {
  7393. var totalPoints = new Array();
  7394. totalPoints.push(points[0].clone());
  7395. Array.prototype.push.apply(totalPoints, points);
  7396. totalPoints.push(points[points.length - 1].clone());
  7397. for (var i = 0; i < totalPoints.length - 3; i++) {
  7398. amount = 0;
  7399. for (var c = 0; c < nbPoints; c++) {
  7400. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7401. amount += step;
  7402. }
  7403. }
  7404. i--;
  7405. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7406. }
  7407. return new Curve3(catmullRom);
  7408. };
  7409. /**
  7410. * Returns the Curve3 stored array of successive Vector3
  7411. */
  7412. Curve3.prototype.getPoints = function () {
  7413. return this._points;
  7414. };
  7415. /**
  7416. * Returns the computed length (float) of the curve.
  7417. */
  7418. Curve3.prototype.length = function () {
  7419. return this._length;
  7420. };
  7421. /**
  7422. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7423. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7424. * curveA and curveB keep unchanged.
  7425. */
  7426. Curve3.prototype.continue = function (curve) {
  7427. var lastPoint = this._points[this._points.length - 1];
  7428. var continuedPoints = this._points.slice();
  7429. var curvePoints = curve.getPoints();
  7430. for (var i = 1; i < curvePoints.length; i++) {
  7431. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7432. }
  7433. var continuedCurve = new Curve3(continuedPoints);
  7434. return continuedCurve;
  7435. };
  7436. Curve3.prototype._computeLength = function (path) {
  7437. var l = 0;
  7438. for (var i = 1; i < path.length; i++) {
  7439. l += (path[i].subtract(path[i - 1])).length();
  7440. }
  7441. return l;
  7442. };
  7443. return Curve3;
  7444. }());
  7445. BABYLON.Curve3 = Curve3;
  7446. // Vertex formats
  7447. var PositionNormalVertex = /** @class */ (function () {
  7448. function PositionNormalVertex(position, normal) {
  7449. if (position === void 0) { position = Vector3.Zero(); }
  7450. if (normal === void 0) { normal = Vector3.Up(); }
  7451. this.position = position;
  7452. this.normal = normal;
  7453. }
  7454. PositionNormalVertex.prototype.clone = function () {
  7455. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7456. };
  7457. return PositionNormalVertex;
  7458. }());
  7459. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7460. var PositionNormalTextureVertex = /** @class */ (function () {
  7461. function PositionNormalTextureVertex(position, normal, uv) {
  7462. if (position === void 0) { position = Vector3.Zero(); }
  7463. if (normal === void 0) { normal = Vector3.Up(); }
  7464. if (uv === void 0) { uv = Vector2.Zero(); }
  7465. this.position = position;
  7466. this.normal = normal;
  7467. this.uv = uv;
  7468. }
  7469. PositionNormalTextureVertex.prototype.clone = function () {
  7470. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7471. };
  7472. return PositionNormalTextureVertex;
  7473. }());
  7474. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7475. // Temporary pre-allocated objects for engine internal use
  7476. // usage in any internal function :
  7477. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7478. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7479. var Tmp = /** @class */ (function () {
  7480. function Tmp() {
  7481. }
  7482. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7483. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7484. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7485. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7486. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7487. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7488. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7489. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7490. Matrix.Zero(), Matrix.Zero(),
  7491. Matrix.Zero(), Matrix.Zero(),
  7492. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7493. return Tmp;
  7494. }());
  7495. BABYLON.Tmp = Tmp;
  7496. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7497. var MathTmp = /** @class */ (function () {
  7498. function MathTmp() {
  7499. }
  7500. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7501. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7502. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7503. return MathTmp;
  7504. }());
  7505. })(BABYLON || (BABYLON = {}));
  7506. //# sourceMappingURL=babylon.math.js.map
  7507. var BABYLON;
  7508. (function (BABYLON) {
  7509. var Scalar = /** @class */ (function () {
  7510. function Scalar() {
  7511. }
  7512. /**
  7513. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7514. */
  7515. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7516. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7517. var num = a - b;
  7518. return -epsilon <= num && num <= epsilon;
  7519. };
  7520. /**
  7521. * Returns a string : the upper case translation of the number i to hexadecimal.
  7522. */
  7523. Scalar.ToHex = function (i) {
  7524. var str = i.toString(16);
  7525. if (i <= 15) {
  7526. return ("0" + str).toUpperCase();
  7527. }
  7528. return str.toUpperCase();
  7529. };
  7530. /**
  7531. * Returns -1 if value is negative and +1 is value is positive.
  7532. * Returns the value itself if it's equal to zero.
  7533. */
  7534. Scalar.Sign = function (value) {
  7535. value = +value; // convert to a number
  7536. if (value === 0 || isNaN(value))
  7537. return value;
  7538. return value > 0 ? 1 : -1;
  7539. };
  7540. /**
  7541. * Returns the value itself if it's between min and max.
  7542. * Returns min if the value is lower than min.
  7543. * Returns max if the value is greater than max.
  7544. */
  7545. Scalar.Clamp = function (value, min, max) {
  7546. if (min === void 0) { min = 0; }
  7547. if (max === void 0) { max = 1; }
  7548. return Math.min(max, Math.max(min, value));
  7549. };
  7550. /**
  7551. * Returns the log2 of value.
  7552. */
  7553. Scalar.Log2 = function (value) {
  7554. return Math.log(value) * Math.LOG2E;
  7555. };
  7556. /**
  7557. * Loops the value, so that it is never larger than length and never smaller than 0.
  7558. *
  7559. * This is similar to the modulo operator but it works with floating point numbers.
  7560. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7561. * With t = 5 and length = 2.5, the result would be 0.0.
  7562. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7563. */
  7564. Scalar.Repeat = function (value, length) {
  7565. return value - Math.floor(value / length) * length;
  7566. };
  7567. /**
  7568. * Normalize the value between 0.0 and 1.0 using min and max values
  7569. */
  7570. Scalar.Normalize = function (value, min, max) {
  7571. return (value - min) / (max - min);
  7572. };
  7573. /**
  7574. * Denormalize the value from 0.0 and 1.0 using min and max values
  7575. */
  7576. Scalar.Denormalize = function (normalized, min, max) {
  7577. return (normalized * (max - min) + min);
  7578. };
  7579. /**
  7580. * Calculates the shortest difference between two given angles given in degrees.
  7581. */
  7582. Scalar.DeltaAngle = function (current, target) {
  7583. var num = Scalar.Repeat(target - current, 360.0);
  7584. if (num > 180.0) {
  7585. num -= 360.0;
  7586. }
  7587. return num;
  7588. };
  7589. /**
  7590. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7591. *
  7592. * The returned value will move back and forth between 0 and length
  7593. */
  7594. Scalar.PingPong = function (tx, length) {
  7595. var t = Scalar.Repeat(tx, length * 2.0);
  7596. return length - Math.abs(t - length);
  7597. };
  7598. /**
  7599. * Interpolates between min and max with smoothing at the limits.
  7600. *
  7601. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7602. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7603. */
  7604. Scalar.SmoothStep = function (from, to, tx) {
  7605. var t = Scalar.Clamp(tx);
  7606. t = -2.0 * t * t * t + 3.0 * t * t;
  7607. return to * t + from * (1.0 - t);
  7608. };
  7609. /**
  7610. * Moves a value current towards target.
  7611. *
  7612. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7613. * Negative values of maxDelta pushes the value away from target.
  7614. */
  7615. Scalar.MoveTowards = function (current, target, maxDelta) {
  7616. var result = 0;
  7617. if (Math.abs(target - current) <= maxDelta) {
  7618. result = target;
  7619. }
  7620. else {
  7621. result = current + Scalar.Sign(target - current) * maxDelta;
  7622. }
  7623. return result;
  7624. };
  7625. /**
  7626. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7627. *
  7628. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7629. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7630. */
  7631. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7632. var num = Scalar.DeltaAngle(current, target);
  7633. var result = 0;
  7634. if (-maxDelta < num && num < maxDelta) {
  7635. result = target;
  7636. }
  7637. else {
  7638. target = current + num;
  7639. result = Scalar.MoveTowards(current, target, maxDelta);
  7640. }
  7641. return result;
  7642. };
  7643. /**
  7644. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7645. */
  7646. Scalar.Lerp = function (start, end, amount) {
  7647. return start + ((end - start) * amount);
  7648. };
  7649. /**
  7650. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7651. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7652. */
  7653. Scalar.LerpAngle = function (start, end, amount) {
  7654. var num = Scalar.Repeat(end - start, 360.0);
  7655. if (num > 180.0) {
  7656. num -= 360.0;
  7657. }
  7658. return start + num * Scalar.Clamp(amount);
  7659. };
  7660. /**
  7661. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7662. */
  7663. Scalar.InverseLerp = function (a, b, value) {
  7664. var result = 0;
  7665. if (a != b) {
  7666. result = Scalar.Clamp((value - a) / (b - a));
  7667. }
  7668. else {
  7669. result = 0.0;
  7670. }
  7671. return result;
  7672. };
  7673. /**
  7674. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7675. */
  7676. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7677. var squared = amount * amount;
  7678. var cubed = amount * squared;
  7679. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7680. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7681. var part3 = (cubed - (2.0 * squared)) + amount;
  7682. var part4 = cubed - squared;
  7683. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7684. };
  7685. /**
  7686. * Returns a random float number between and min and max values
  7687. */
  7688. Scalar.RandomRange = function (min, max) {
  7689. if (min === max)
  7690. return min;
  7691. return ((Math.random() * (max - min)) + min);
  7692. };
  7693. /**
  7694. * This function returns percentage of a number in a given range.
  7695. *
  7696. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7697. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7698. */
  7699. Scalar.RangeToPercent = function (number, min, max) {
  7700. return ((number - min) / (max - min));
  7701. };
  7702. /**
  7703. * This function returns number that corresponds to the percentage in a given range.
  7704. *
  7705. * PercentToRange(0.34,0,100) will return 34.
  7706. */
  7707. Scalar.PercentToRange = function (percent, min, max) {
  7708. return ((max - min) * percent + min);
  7709. };
  7710. /**
  7711. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7712. * @param angle The angle to normalize in radian.
  7713. * @return The converted angle.
  7714. */
  7715. Scalar.NormalizeRadians = function (angle) {
  7716. // More precise but slower version kept for reference.
  7717. // angle = angle % Tools.TwoPi;
  7718. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7719. //if (angle > Math.PI) {
  7720. // angle -= Tools.TwoPi;
  7721. //}
  7722. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7723. return angle;
  7724. };
  7725. /**
  7726. * Two pi constants convenient for computation.
  7727. */
  7728. Scalar.TwoPi = Math.PI * 2;
  7729. return Scalar;
  7730. }());
  7731. BABYLON.Scalar = Scalar;
  7732. })(BABYLON || (BABYLON = {}));
  7733. //# sourceMappingURL=babylon.math.scalar.js.map
  7734. //# sourceMappingURL=babylon.mixins.js.map
  7735. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7736. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7737. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7738. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7739. //# sourceMappingURL=babylon.webgl2.js.map
  7740. var BABYLON;
  7741. (function (BABYLON) {
  7742. var __decoratorInitialStore = {};
  7743. var __mergedStore = {};
  7744. var _copySource = function (creationFunction, source, instanciate) {
  7745. var destination = creationFunction();
  7746. // Tags
  7747. if (BABYLON.Tags) {
  7748. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7749. }
  7750. var classStore = getMergedStore(destination);
  7751. // Properties
  7752. for (var property in classStore) {
  7753. var propertyDescriptor = classStore[property];
  7754. var sourceProperty = source[property];
  7755. var propertyType = propertyDescriptor.type;
  7756. if (sourceProperty !== undefined && sourceProperty !== null) {
  7757. switch (propertyType) {
  7758. case 0: // Value
  7759. case 6: // Mesh reference
  7760. case 11: // Camera reference
  7761. destination[property] = sourceProperty;
  7762. break;
  7763. case 1: // Texture
  7764. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7765. break;
  7766. case 2: // Color3
  7767. case 3: // FresnelParameters
  7768. case 4: // Vector2
  7769. case 5: // Vector3
  7770. case 7: // Color Curves
  7771. case 10: // Quaternion
  7772. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7773. break;
  7774. }
  7775. }
  7776. }
  7777. return destination;
  7778. };
  7779. function getDirectStore(target) {
  7780. var classKey = target.getClassName();
  7781. if (!__decoratorInitialStore[classKey]) {
  7782. __decoratorInitialStore[classKey] = {};
  7783. }
  7784. return __decoratorInitialStore[classKey];
  7785. }
  7786. /**
  7787. * Return the list of properties flagged as serializable
  7788. * @param target: host object
  7789. */
  7790. function getMergedStore(target) {
  7791. var classKey = target.getClassName();
  7792. if (__mergedStore[classKey]) {
  7793. return __mergedStore[classKey];
  7794. }
  7795. __mergedStore[classKey] = {};
  7796. var store = __mergedStore[classKey];
  7797. var currentTarget = target;
  7798. var currentKey = classKey;
  7799. while (currentKey) {
  7800. var initialStore = __decoratorInitialStore[currentKey];
  7801. for (var property in initialStore) {
  7802. store[property] = initialStore[property];
  7803. }
  7804. var parent_1 = void 0;
  7805. var done = false;
  7806. do {
  7807. parent_1 = Object.getPrototypeOf(currentTarget);
  7808. if (!parent_1.getClassName) {
  7809. done = true;
  7810. break;
  7811. }
  7812. if (parent_1.getClassName() !== currentKey) {
  7813. break;
  7814. }
  7815. currentTarget = parent_1;
  7816. } while (parent_1);
  7817. if (done) {
  7818. break;
  7819. }
  7820. currentKey = parent_1.getClassName();
  7821. currentTarget = parent_1;
  7822. }
  7823. return store;
  7824. }
  7825. function generateSerializableMember(type, sourceName) {
  7826. return function (target, propertyKey) {
  7827. var classStore = getDirectStore(target);
  7828. if (!classStore[propertyKey]) {
  7829. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7830. }
  7831. };
  7832. }
  7833. function generateExpandMember(setCallback, targetKey) {
  7834. if (targetKey === void 0) { targetKey = null; }
  7835. return function (target, propertyKey) {
  7836. var key = targetKey || ("_" + propertyKey);
  7837. Object.defineProperty(target, propertyKey, {
  7838. get: function () {
  7839. return this[key];
  7840. },
  7841. set: function (value) {
  7842. if (this[key] === value) {
  7843. return;
  7844. }
  7845. this[key] = value;
  7846. target[setCallback].apply(this);
  7847. },
  7848. enumerable: true,
  7849. configurable: true
  7850. });
  7851. };
  7852. }
  7853. function expandToProperty(callback, targetKey) {
  7854. if (targetKey === void 0) { targetKey = null; }
  7855. return generateExpandMember(callback, targetKey);
  7856. }
  7857. BABYLON.expandToProperty = expandToProperty;
  7858. function serialize(sourceName) {
  7859. return generateSerializableMember(0, sourceName); // value member
  7860. }
  7861. BABYLON.serialize = serialize;
  7862. function serializeAsTexture(sourceName) {
  7863. return generateSerializableMember(1, sourceName); // texture member
  7864. }
  7865. BABYLON.serializeAsTexture = serializeAsTexture;
  7866. function serializeAsColor3(sourceName) {
  7867. return generateSerializableMember(2, sourceName); // color3 member
  7868. }
  7869. BABYLON.serializeAsColor3 = serializeAsColor3;
  7870. function serializeAsFresnelParameters(sourceName) {
  7871. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7872. }
  7873. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7874. function serializeAsVector2(sourceName) {
  7875. return generateSerializableMember(4, sourceName); // vector2 member
  7876. }
  7877. BABYLON.serializeAsVector2 = serializeAsVector2;
  7878. function serializeAsVector3(sourceName) {
  7879. return generateSerializableMember(5, sourceName); // vector3 member
  7880. }
  7881. BABYLON.serializeAsVector3 = serializeAsVector3;
  7882. function serializeAsMeshReference(sourceName) {
  7883. return generateSerializableMember(6, sourceName); // mesh reference member
  7884. }
  7885. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7886. function serializeAsColorCurves(sourceName) {
  7887. return generateSerializableMember(7, sourceName); // color curves
  7888. }
  7889. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7890. function serializeAsColor4(sourceName) {
  7891. return generateSerializableMember(8, sourceName); // color 4
  7892. }
  7893. BABYLON.serializeAsColor4 = serializeAsColor4;
  7894. function serializeAsImageProcessingConfiguration(sourceName) {
  7895. return generateSerializableMember(9, sourceName); // image processing
  7896. }
  7897. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7898. function serializeAsQuaternion(sourceName) {
  7899. return generateSerializableMember(10, sourceName); // quaternion member
  7900. }
  7901. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7902. /**
  7903. * Decorator used to define property that can be serialized as reference to a camera
  7904. * @param sourceName defines the name of the property to decorate
  7905. */
  7906. function serializeAsCameraReference(sourceName) {
  7907. return generateSerializableMember(11, sourceName); // camera reference member
  7908. }
  7909. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7910. var SerializationHelper = /** @class */ (function () {
  7911. function SerializationHelper() {
  7912. }
  7913. SerializationHelper.Serialize = function (entity, serializationObject) {
  7914. if (!serializationObject) {
  7915. serializationObject = {};
  7916. }
  7917. // Tags
  7918. if (BABYLON.Tags) {
  7919. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7920. }
  7921. var serializedProperties = getMergedStore(entity);
  7922. // Properties
  7923. for (var property in serializedProperties) {
  7924. var propertyDescriptor = serializedProperties[property];
  7925. var targetPropertyName = propertyDescriptor.sourceName || property;
  7926. var propertyType = propertyDescriptor.type;
  7927. var sourceProperty = entity[property];
  7928. if (sourceProperty !== undefined && sourceProperty !== null) {
  7929. switch (propertyType) {
  7930. case 0: // Value
  7931. serializationObject[targetPropertyName] = sourceProperty;
  7932. break;
  7933. case 1: // Texture
  7934. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7935. break;
  7936. case 2: // Color3
  7937. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7938. break;
  7939. case 3: // FresnelParameters
  7940. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7941. break;
  7942. case 4: // Vector2
  7943. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7944. break;
  7945. case 5: // Vector3
  7946. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7947. break;
  7948. case 6: // Mesh reference
  7949. serializationObject[targetPropertyName] = sourceProperty.id;
  7950. break;
  7951. case 7: // Color Curves
  7952. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7953. break;
  7954. case 8: // Color 4
  7955. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7956. break;
  7957. case 9: // Image Processing
  7958. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7959. break;
  7960. case 10: // Quaternion
  7961. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7962. break;
  7963. case 11: // Camera reference
  7964. serializationObject[targetPropertyName] = sourceProperty.id;
  7965. break;
  7966. }
  7967. }
  7968. }
  7969. return serializationObject;
  7970. };
  7971. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7972. if (rootUrl === void 0) { rootUrl = null; }
  7973. var destination = creationFunction();
  7974. if (!rootUrl) {
  7975. rootUrl = "";
  7976. }
  7977. // Tags
  7978. if (BABYLON.Tags) {
  7979. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7980. }
  7981. var classStore = getMergedStore(destination);
  7982. // Properties
  7983. for (var property in classStore) {
  7984. var propertyDescriptor = classStore[property];
  7985. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7986. var propertyType = propertyDescriptor.type;
  7987. if (sourceProperty !== undefined && sourceProperty !== null) {
  7988. var dest = destination;
  7989. switch (propertyType) {
  7990. case 0: // Value
  7991. dest[property] = sourceProperty;
  7992. break;
  7993. case 1: // Texture
  7994. if (scene) {
  7995. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7996. }
  7997. break;
  7998. case 2: // Color3
  7999. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8000. break;
  8001. case 3: // FresnelParameters
  8002. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8003. break;
  8004. case 4: // Vector2
  8005. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8006. break;
  8007. case 5: // Vector3
  8008. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8009. break;
  8010. case 6: // Mesh reference
  8011. if (scene) {
  8012. dest[property] = scene.getLastMeshByID(sourceProperty);
  8013. }
  8014. break;
  8015. case 7: // Color Curves
  8016. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8017. break;
  8018. case 8: // Color 4
  8019. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8020. break;
  8021. case 9: // Image Processing
  8022. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8023. break;
  8024. case 10: // Quaternion
  8025. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8026. break;
  8027. case 11: // Camera reference
  8028. if (scene) {
  8029. dest[property] = scene.getCameraByID(sourceProperty);
  8030. }
  8031. break;
  8032. }
  8033. }
  8034. }
  8035. return destination;
  8036. };
  8037. SerializationHelper.Clone = function (creationFunction, source) {
  8038. return _copySource(creationFunction, source, false);
  8039. };
  8040. SerializationHelper.Instanciate = function (creationFunction, source) {
  8041. return _copySource(creationFunction, source, true);
  8042. };
  8043. return SerializationHelper;
  8044. }());
  8045. BABYLON.SerializationHelper = SerializationHelper;
  8046. })(BABYLON || (BABYLON = {}));
  8047. //# sourceMappingURL=babylon.decorators.js.map
  8048. var BABYLON;
  8049. (function (BABYLON) {
  8050. /**
  8051. * Wrapper class for promise with external resolve and reject.
  8052. */
  8053. var Deferred = /** @class */ (function () {
  8054. /**
  8055. * Constructor for this deferred object.
  8056. */
  8057. function Deferred() {
  8058. var _this = this;
  8059. this.promise = new Promise(function (resolve, reject) {
  8060. _this._resolve = resolve;
  8061. _this._reject = reject;
  8062. });
  8063. }
  8064. Object.defineProperty(Deferred.prototype, "resolve", {
  8065. /**
  8066. * The resolve method of the promise associated with this deferred object.
  8067. */
  8068. get: function () {
  8069. return this._resolve;
  8070. },
  8071. enumerable: true,
  8072. configurable: true
  8073. });
  8074. Object.defineProperty(Deferred.prototype, "reject", {
  8075. /**
  8076. * The reject method of the promise associated with this deferred object.
  8077. */
  8078. get: function () {
  8079. return this._reject;
  8080. },
  8081. enumerable: true,
  8082. configurable: true
  8083. });
  8084. return Deferred;
  8085. }());
  8086. BABYLON.Deferred = Deferred;
  8087. })(BABYLON || (BABYLON = {}));
  8088. //# sourceMappingURL=babylon.deferred.js.map
  8089. var BABYLON;
  8090. (function (BABYLON) {
  8091. /**
  8092. * A class serves as a medium between the observable and its observers
  8093. */
  8094. var EventState = /** @class */ (function () {
  8095. /**
  8096. * Create a new EventState
  8097. * @param mask defines the mask associated with this state
  8098. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8099. * @param target defines the original target of the state
  8100. * @param currentTarget defines the current target of the state
  8101. */
  8102. function EventState(mask, skipNextObservers, target, currentTarget) {
  8103. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8104. this.initalize(mask, skipNextObservers, target, currentTarget);
  8105. }
  8106. /**
  8107. * Initialize the current event state
  8108. * @param mask defines the mask associated with this state
  8109. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8110. * @param target defines the original target of the state
  8111. * @param currentTarget defines the current target of the state
  8112. * @returns the current event state
  8113. */
  8114. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8115. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8116. this.mask = mask;
  8117. this.skipNextObservers = skipNextObservers;
  8118. this.target = target;
  8119. this.currentTarget = currentTarget;
  8120. return this;
  8121. };
  8122. return EventState;
  8123. }());
  8124. BABYLON.EventState = EventState;
  8125. /**
  8126. * Represent an Observer registered to a given Observable object.
  8127. */
  8128. var Observer = /** @class */ (function () {
  8129. /**
  8130. * Creates a new observer
  8131. * @param callback defines the callback to call when the observer is notified
  8132. * @param mask defines the mask of the observer (used to filter notifications)
  8133. * @param scope defines the current scope used to restore the JS context
  8134. */
  8135. function Observer(
  8136. /**
  8137. * Defines the callback to call when the observer is notified
  8138. */
  8139. callback,
  8140. /**
  8141. * Defines the mask of the observer (used to filter notifications)
  8142. */
  8143. mask,
  8144. /**
  8145. * Defines the current scope used to restore the JS context
  8146. */
  8147. scope) {
  8148. if (scope === void 0) { scope = null; }
  8149. this.callback = callback;
  8150. this.mask = mask;
  8151. this.scope = scope;
  8152. /** @hidden */
  8153. this._willBeUnregistered = false;
  8154. /**
  8155. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8156. */
  8157. this.unregisterOnNextCall = false;
  8158. }
  8159. return Observer;
  8160. }());
  8161. BABYLON.Observer = Observer;
  8162. /**
  8163. * Represent a list of observers registered to multiple Observables object.
  8164. */
  8165. var MultiObserver = /** @class */ (function () {
  8166. function MultiObserver() {
  8167. }
  8168. /**
  8169. * Release associated resources
  8170. */
  8171. MultiObserver.prototype.dispose = function () {
  8172. if (this._observers && this._observables) {
  8173. for (var index = 0; index < this._observers.length; index++) {
  8174. this._observables[index].remove(this._observers[index]);
  8175. }
  8176. }
  8177. this._observers = null;
  8178. this._observables = null;
  8179. };
  8180. /**
  8181. * Raise a callback when one of the observable will notify
  8182. * @param observables defines a list of observables to watch
  8183. * @param callback defines the callback to call on notification
  8184. * @param mask defines the mask used to filter notifications
  8185. * @param scope defines the current scope used to restore the JS context
  8186. * @returns the new MultiObserver
  8187. */
  8188. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8189. if (mask === void 0) { mask = -1; }
  8190. if (scope === void 0) { scope = null; }
  8191. var result = new MultiObserver();
  8192. result._observers = new Array();
  8193. result._observables = observables;
  8194. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8195. var observable = observables_1[_i];
  8196. var observer = observable.add(callback, mask, false, scope);
  8197. if (observer) {
  8198. result._observers.push(observer);
  8199. }
  8200. }
  8201. return result;
  8202. };
  8203. return MultiObserver;
  8204. }());
  8205. BABYLON.MultiObserver = MultiObserver;
  8206. /**
  8207. * The Observable class is a simple implementation of the Observable pattern.
  8208. *
  8209. * 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.
  8210. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8211. * 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).
  8212. * 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.
  8213. */
  8214. var Observable = /** @class */ (function () {
  8215. /**
  8216. * Creates a new observable
  8217. * @param onObserverAdded defines a callback to call when a new observer is added
  8218. */
  8219. function Observable(onObserverAdded) {
  8220. this._observers = new Array();
  8221. this._eventState = new EventState(0);
  8222. if (onObserverAdded) {
  8223. this._onObserverAdded = onObserverAdded;
  8224. }
  8225. }
  8226. /**
  8227. * Create a new Observer with the specified callback
  8228. * @param callback the callback that will be executed for that Observer
  8229. * @param mask the mask used to filter observers
  8230. * @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.
  8231. * @param scope optional scope for the callback to be called from
  8232. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8233. * @returns the new observer created for the callback
  8234. */
  8235. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8236. if (mask === void 0) { mask = -1; }
  8237. if (insertFirst === void 0) { insertFirst = false; }
  8238. if (scope === void 0) { scope = null; }
  8239. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8240. if (!callback) {
  8241. return null;
  8242. }
  8243. var observer = new Observer(callback, mask, scope);
  8244. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8245. if (insertFirst) {
  8246. this._observers.unshift(observer);
  8247. }
  8248. else {
  8249. this._observers.push(observer);
  8250. }
  8251. if (this._onObserverAdded) {
  8252. this._onObserverAdded(observer);
  8253. }
  8254. return observer;
  8255. };
  8256. /**
  8257. * Create a new Observer with the specified callback and unregisters after the next notification
  8258. * @param callback the callback that will be executed for that Observer
  8259. * @returns the new observer created for the callback
  8260. */
  8261. Observable.prototype.addOnce = function (callback) {
  8262. return this.add(callback, undefined, undefined, undefined, true);
  8263. };
  8264. /**
  8265. * Remove an Observer from the Observable object
  8266. * @param observer the instance of the Observer to remove
  8267. * @returns false if it doesn't belong to this Observable
  8268. */
  8269. Observable.prototype.remove = function (observer) {
  8270. if (!observer) {
  8271. return false;
  8272. }
  8273. var index = this._observers.indexOf(observer);
  8274. if (index !== -1) {
  8275. this._deferUnregister(observer);
  8276. return true;
  8277. }
  8278. return false;
  8279. };
  8280. /**
  8281. * Remove a callback from the Observable object
  8282. * @param callback the callback to remove
  8283. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8284. * @returns false if it doesn't belong to this Observable
  8285. */
  8286. Observable.prototype.removeCallback = function (callback, scope) {
  8287. for (var index = 0; index < this._observers.length; index++) {
  8288. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8289. this._deferUnregister(this._observers[index]);
  8290. return true;
  8291. }
  8292. }
  8293. return false;
  8294. };
  8295. Observable.prototype._deferUnregister = function (observer) {
  8296. var _this = this;
  8297. observer.unregisterOnNextCall = false;
  8298. observer._willBeUnregistered = true;
  8299. BABYLON.Tools.SetImmediate(function () {
  8300. _this._remove(observer);
  8301. });
  8302. };
  8303. // This should only be called when not iterating over _observers to avoid callback skipping.
  8304. // Removes an observer from the _observer Array.
  8305. Observable.prototype._remove = function (observer) {
  8306. if (!observer) {
  8307. return false;
  8308. }
  8309. var index = this._observers.indexOf(observer);
  8310. if (index !== -1) {
  8311. this._observers.splice(index, 1);
  8312. return true;
  8313. }
  8314. return false;
  8315. };
  8316. /**
  8317. * Notify all Observers by calling their respective callback with the given data
  8318. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8319. * @param eventData defines the data to send to all observers
  8320. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8321. * @param target defines the original target of the state
  8322. * @param currentTarget defines the current target of the state
  8323. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8324. */
  8325. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8326. if (mask === void 0) { mask = -1; }
  8327. if (!this._observers.length) {
  8328. return true;
  8329. }
  8330. var state = this._eventState;
  8331. state.mask = mask;
  8332. state.target = target;
  8333. state.currentTarget = currentTarget;
  8334. state.skipNextObservers = false;
  8335. state.lastReturnValue = eventData;
  8336. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8337. var obs = _a[_i];
  8338. if (obs._willBeUnregistered) {
  8339. continue;
  8340. }
  8341. if (obs.mask & mask) {
  8342. if (obs.scope) {
  8343. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8344. }
  8345. else {
  8346. state.lastReturnValue = obs.callback(eventData, state);
  8347. }
  8348. if (obs.unregisterOnNextCall) {
  8349. this._deferUnregister(obs);
  8350. }
  8351. }
  8352. if (state.skipNextObservers) {
  8353. return false;
  8354. }
  8355. }
  8356. return true;
  8357. };
  8358. /**
  8359. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8360. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8361. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8362. * and it is crucial that all callbacks will be executed.
  8363. * The order of the callbacks is kept, callbacks are not executed parallel.
  8364. *
  8365. * @param eventData The data to be sent to each callback
  8366. * @param mask is used to filter observers defaults to -1
  8367. * @param target defines the callback target (see EventState)
  8368. * @param currentTarget defines he current object in the bubbling phase
  8369. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8370. */
  8371. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8372. var _this = this;
  8373. if (mask === void 0) { mask = -1; }
  8374. // create an empty promise
  8375. var p = Promise.resolve(eventData);
  8376. // no observers? return this promise.
  8377. if (!this._observers.length) {
  8378. return p;
  8379. }
  8380. var state = this._eventState;
  8381. state.mask = mask;
  8382. state.target = target;
  8383. state.currentTarget = currentTarget;
  8384. state.skipNextObservers = false;
  8385. // execute one callback after another (not using Promise.all, the order is important)
  8386. this._observers.forEach(function (obs) {
  8387. if (state.skipNextObservers) {
  8388. return;
  8389. }
  8390. if (obs._willBeUnregistered) {
  8391. return;
  8392. }
  8393. if (obs.mask & mask) {
  8394. if (obs.scope) {
  8395. p = p.then(function (lastReturnedValue) {
  8396. state.lastReturnValue = lastReturnedValue;
  8397. return obs.callback.apply(obs.scope, [eventData, state]);
  8398. });
  8399. }
  8400. else {
  8401. p = p.then(function (lastReturnedValue) {
  8402. state.lastReturnValue = lastReturnedValue;
  8403. return obs.callback(eventData, state);
  8404. });
  8405. }
  8406. if (obs.unregisterOnNextCall) {
  8407. _this._deferUnregister(obs);
  8408. }
  8409. }
  8410. });
  8411. // return the eventData
  8412. return p.then(function () { return eventData; });
  8413. };
  8414. /**
  8415. * Notify a specific observer
  8416. * @param observer defines the observer to notify
  8417. * @param eventData defines the data to be sent to each callback
  8418. * @param mask is used to filter observers defaults to -1
  8419. */
  8420. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8421. if (mask === void 0) { mask = -1; }
  8422. var state = this._eventState;
  8423. state.mask = mask;
  8424. state.skipNextObservers = false;
  8425. observer.callback(eventData, state);
  8426. };
  8427. /**
  8428. * Gets a boolean indicating if the observable has at least one observer
  8429. * @returns true is the Observable has at least one Observer registered
  8430. */
  8431. Observable.prototype.hasObservers = function () {
  8432. return this._observers.length > 0;
  8433. };
  8434. /**
  8435. * Clear the list of observers
  8436. */
  8437. Observable.prototype.clear = function () {
  8438. this._observers = new Array();
  8439. this._onObserverAdded = null;
  8440. };
  8441. /**
  8442. * Clone the current observable
  8443. * @returns a new observable
  8444. */
  8445. Observable.prototype.clone = function () {
  8446. var result = new Observable();
  8447. result._observers = this._observers.slice(0);
  8448. return result;
  8449. };
  8450. /**
  8451. * Does this observable handles observer registered with a given mask
  8452. * @param mask defines the mask to be tested
  8453. * @return whether or not one observer registered with the given mask is handeled
  8454. **/
  8455. Observable.prototype.hasSpecificMask = function (mask) {
  8456. if (mask === void 0) { mask = -1; }
  8457. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8458. var obs = _a[_i];
  8459. if (obs.mask & mask || obs.mask === mask) {
  8460. return true;
  8461. }
  8462. }
  8463. return false;
  8464. };
  8465. return Observable;
  8466. }());
  8467. BABYLON.Observable = Observable;
  8468. })(BABYLON || (BABYLON = {}));
  8469. //# sourceMappingURL=babylon.observable.js.map
  8470. var BABYLON;
  8471. (function (BABYLON) {
  8472. var SmartArray = /** @class */ (function () {
  8473. function SmartArray(capacity) {
  8474. this.length = 0;
  8475. this.data = new Array(capacity);
  8476. this._id = SmartArray._GlobalId++;
  8477. }
  8478. SmartArray.prototype.push = function (value) {
  8479. this.data[this.length++] = value;
  8480. if (this.length > this.data.length) {
  8481. this.data.length *= 2;
  8482. }
  8483. };
  8484. SmartArray.prototype.forEach = function (func) {
  8485. for (var index = 0; index < this.length; index++) {
  8486. func(this.data[index]);
  8487. }
  8488. };
  8489. SmartArray.prototype.sort = function (compareFn) {
  8490. this.data.sort(compareFn);
  8491. };
  8492. SmartArray.prototype.reset = function () {
  8493. this.length = 0;
  8494. };
  8495. SmartArray.prototype.dispose = function () {
  8496. this.reset();
  8497. if (this.data) {
  8498. this.data.length = 0;
  8499. this.data = [];
  8500. }
  8501. };
  8502. SmartArray.prototype.concat = function (array) {
  8503. if (array.length === 0) {
  8504. return;
  8505. }
  8506. if (this.length + array.length > this.data.length) {
  8507. this.data.length = (this.length + array.length) * 2;
  8508. }
  8509. for (var index = 0; index < array.length; index++) {
  8510. this.data[this.length++] = (array.data || array)[index];
  8511. }
  8512. };
  8513. SmartArray.prototype.indexOf = function (value) {
  8514. var position = this.data.indexOf(value);
  8515. if (position >= this.length) {
  8516. return -1;
  8517. }
  8518. return position;
  8519. };
  8520. SmartArray.prototype.contains = function (value) {
  8521. return this.data.indexOf(value) !== -1;
  8522. };
  8523. // Statics
  8524. SmartArray._GlobalId = 0;
  8525. return SmartArray;
  8526. }());
  8527. BABYLON.SmartArray = SmartArray;
  8528. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8529. __extends(SmartArrayNoDuplicate, _super);
  8530. function SmartArrayNoDuplicate() {
  8531. var _this = _super !== null && _super.apply(this, arguments) || this;
  8532. _this._duplicateId = 0;
  8533. return _this;
  8534. }
  8535. SmartArrayNoDuplicate.prototype.push = function (value) {
  8536. _super.prototype.push.call(this, value);
  8537. if (!value.__smartArrayFlags) {
  8538. value.__smartArrayFlags = {};
  8539. }
  8540. value.__smartArrayFlags[this._id] = this._duplicateId;
  8541. };
  8542. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8543. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8544. return false;
  8545. }
  8546. this.push(value);
  8547. return true;
  8548. };
  8549. SmartArrayNoDuplicate.prototype.reset = function () {
  8550. _super.prototype.reset.call(this);
  8551. this._duplicateId++;
  8552. };
  8553. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8554. if (array.length === 0) {
  8555. return;
  8556. }
  8557. if (this.length + array.length > this.data.length) {
  8558. this.data.length = (this.length + array.length) * 2;
  8559. }
  8560. for (var index = 0; index < array.length; index++) {
  8561. var item = (array.data || array)[index];
  8562. this.pushNoDuplicate(item);
  8563. }
  8564. };
  8565. return SmartArrayNoDuplicate;
  8566. }(SmartArray));
  8567. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8568. })(BABYLON || (BABYLON = {}));
  8569. //# sourceMappingURL=babylon.smartArray.js.map
  8570. var BABYLON;
  8571. (function (BABYLON) {
  8572. /** Class used to store color gradient */
  8573. var ColorGradient = /** @class */ (function () {
  8574. function ColorGradient() {
  8575. }
  8576. /**
  8577. * Will get a color picked randomly between color1 and color2.
  8578. * If color2 is undefined then color1 will be used
  8579. * @param result defines the target Color4 to store the result in
  8580. */
  8581. ColorGradient.prototype.getColorToRef = function (result) {
  8582. if (!this.color2) {
  8583. result.copyFrom(this.color1);
  8584. return;
  8585. }
  8586. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8587. };
  8588. return ColorGradient;
  8589. }());
  8590. BABYLON.ColorGradient = ColorGradient;
  8591. /** Class used to store factor gradient */
  8592. var FactorGradient = /** @class */ (function () {
  8593. function FactorGradient() {
  8594. }
  8595. /**
  8596. * Will get a number picked randomly between factor1 and factor2.
  8597. * If factor2 is undefined then factor1 will be used
  8598. * @returns the picked number
  8599. */
  8600. FactorGradient.prototype.getFactor = function () {
  8601. if (this.factor2 === undefined) {
  8602. return this.factor1;
  8603. }
  8604. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8605. };
  8606. return FactorGradient;
  8607. }());
  8608. BABYLON.FactorGradient = FactorGradient;
  8609. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8610. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8611. var LoadFileError = /** @class */ (function (_super) {
  8612. __extends(LoadFileError, _super);
  8613. function LoadFileError(message, request) {
  8614. var _this = _super.call(this, message) || this;
  8615. _this.request = request;
  8616. _this.name = "LoadFileError";
  8617. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8618. return _this;
  8619. }
  8620. // Polyfill for Object.setPrototypeOf if necessary.
  8621. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8622. return LoadFileError;
  8623. }(Error));
  8624. BABYLON.LoadFileError = LoadFileError;
  8625. var RetryStrategy = /** @class */ (function () {
  8626. function RetryStrategy() {
  8627. }
  8628. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8629. if (maxRetries === void 0) { maxRetries = 3; }
  8630. if (baseInterval === void 0) { baseInterval = 500; }
  8631. return function (url, request, retryIndex) {
  8632. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8633. return -1;
  8634. }
  8635. return Math.pow(2, retryIndex) * baseInterval;
  8636. };
  8637. };
  8638. return RetryStrategy;
  8639. }());
  8640. BABYLON.RetryStrategy = RetryStrategy;
  8641. // Screenshots
  8642. var screenshotCanvas;
  8643. var cloneValue = function (source, destinationObject) {
  8644. if (!source)
  8645. return null;
  8646. if (source instanceof BABYLON.Mesh) {
  8647. return null;
  8648. }
  8649. if (source instanceof BABYLON.SubMesh) {
  8650. return source.clone(destinationObject);
  8651. }
  8652. else if (source.clone) {
  8653. return source.clone();
  8654. }
  8655. return null;
  8656. };
  8657. var Tools = /** @class */ (function () {
  8658. function Tools() {
  8659. }
  8660. /**
  8661. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8662. * @param u defines the coordinate on X axis
  8663. * @param v defines the coordinate on Y axis
  8664. * @param width defines the width of the source data
  8665. * @param height defines the height of the source data
  8666. * @param pixels defines the source byte array
  8667. * @param color defines the output color
  8668. */
  8669. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8670. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8671. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8672. var position = (wrappedU + wrappedV * width) * 4;
  8673. color.r = pixels[position] / 255;
  8674. color.g = pixels[position + 1] / 255;
  8675. color.b = pixels[position + 2] / 255;
  8676. color.a = pixels[position + 3] / 255;
  8677. };
  8678. /**
  8679. * Interpolates between a and b via alpha
  8680. * @param a The lower value (returned when alpha = 0)
  8681. * @param b The upper value (returned when alpha = 1)
  8682. * @param alpha The interpolation-factor
  8683. * @return The mixed value
  8684. */
  8685. Tools.Mix = function (a, b, alpha) {
  8686. return a * (1 - alpha) + b * alpha;
  8687. };
  8688. Tools.Instantiate = function (className) {
  8689. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8690. return Tools.RegisteredExternalClasses[className];
  8691. }
  8692. var arr = className.split(".");
  8693. var fn = (window || this);
  8694. for (var i = 0, len = arr.length; i < len; i++) {
  8695. fn = fn[arr[i]];
  8696. }
  8697. if (typeof fn !== "function") {
  8698. return null;
  8699. }
  8700. return fn;
  8701. };
  8702. /**
  8703. * Provides a slice function that will work even on IE
  8704. * @param data defines the array to slice
  8705. * @param start defines the start of the data (optional)
  8706. * @param end defines the end of the data (optional)
  8707. * @returns the new sliced array
  8708. */
  8709. Tools.Slice = function (data, start, end) {
  8710. if (data.slice) {
  8711. return data.slice(start, end);
  8712. }
  8713. return Array.prototype.slice.call(data, start, end);
  8714. };
  8715. Tools.SetImmediate = function (action) {
  8716. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8717. window.setImmediate(action);
  8718. }
  8719. else {
  8720. setTimeout(action, 1);
  8721. }
  8722. };
  8723. Tools.IsExponentOfTwo = function (value) {
  8724. var count = 1;
  8725. do {
  8726. count *= 2;
  8727. } while (count < value);
  8728. return count === value;
  8729. };
  8730. /**
  8731. * Returns the nearest 32-bit single precision float representation of a Number
  8732. * @param value A Number. If the parameter is of a different type, it will get converted
  8733. * to a number or to NaN if it cannot be converted
  8734. * @returns number
  8735. */
  8736. Tools.FloatRound = function (value) {
  8737. if (Math.fround) {
  8738. return Math.fround(value);
  8739. }
  8740. return (Tools._tmpFloatArray[0] = value);
  8741. };
  8742. /**
  8743. * Find the next highest power of two.
  8744. * @param x Number to start search from.
  8745. * @return Next highest power of two.
  8746. */
  8747. Tools.CeilingPOT = function (x) {
  8748. x--;
  8749. x |= x >> 1;
  8750. x |= x >> 2;
  8751. x |= x >> 4;
  8752. x |= x >> 8;
  8753. x |= x >> 16;
  8754. x++;
  8755. return x;
  8756. };
  8757. /**
  8758. * Find the next lowest power of two.
  8759. * @param x Number to start search from.
  8760. * @return Next lowest power of two.
  8761. */
  8762. Tools.FloorPOT = function (x) {
  8763. x = x | (x >> 1);
  8764. x = x | (x >> 2);
  8765. x = x | (x >> 4);
  8766. x = x | (x >> 8);
  8767. x = x | (x >> 16);
  8768. return x - (x >> 1);
  8769. };
  8770. /**
  8771. * Find the nearest power of two.
  8772. * @param x Number to start search from.
  8773. * @return Next nearest power of two.
  8774. */
  8775. Tools.NearestPOT = function (x) {
  8776. var c = Tools.CeilingPOT(x);
  8777. var f = Tools.FloorPOT(x);
  8778. return (c - x) > (x - f) ? f : c;
  8779. };
  8780. Tools.GetExponentOfTwo = function (value, max, mode) {
  8781. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8782. var pot;
  8783. switch (mode) {
  8784. case BABYLON.Engine.SCALEMODE_FLOOR:
  8785. pot = Tools.FloorPOT(value);
  8786. break;
  8787. case BABYLON.Engine.SCALEMODE_NEAREST:
  8788. pot = Tools.NearestPOT(value);
  8789. break;
  8790. case BABYLON.Engine.SCALEMODE_CEILING:
  8791. default:
  8792. pot = Tools.CeilingPOT(value);
  8793. break;
  8794. }
  8795. return Math.min(pot, max);
  8796. };
  8797. Tools.GetFilename = function (path) {
  8798. var index = path.lastIndexOf("/");
  8799. if (index < 0)
  8800. return path;
  8801. return path.substring(index + 1);
  8802. };
  8803. /**
  8804. * Extracts the "folder" part of a path (everything before the filename).
  8805. * @param uri The URI to extract the info from
  8806. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8807. * @returns The "folder" part of the path
  8808. */
  8809. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8810. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8811. var index = uri.lastIndexOf("/");
  8812. if (index < 0) {
  8813. if (returnUnchangedIfNoSlash) {
  8814. return uri;
  8815. }
  8816. return "";
  8817. }
  8818. return uri.substring(0, index + 1);
  8819. };
  8820. Tools.GetDOMTextContent = function (element) {
  8821. var result = "";
  8822. var child = element.firstChild;
  8823. while (child) {
  8824. if (child.nodeType === 3) {
  8825. result += child.textContent;
  8826. }
  8827. child = child.nextSibling;
  8828. }
  8829. return result;
  8830. };
  8831. Tools.ToDegrees = function (angle) {
  8832. return angle * 180 / Math.PI;
  8833. };
  8834. Tools.ToRadians = function (angle) {
  8835. return angle * Math.PI / 180;
  8836. };
  8837. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8838. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8839. var output = "";
  8840. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8841. var i = 0;
  8842. var bytes = new Uint8Array(buffer);
  8843. while (i < bytes.length) {
  8844. chr1 = bytes[i++];
  8845. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8846. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8847. enc1 = chr1 >> 2;
  8848. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8849. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8850. enc4 = chr3 & 63;
  8851. if (isNaN(chr2)) {
  8852. enc3 = enc4 = 64;
  8853. }
  8854. else if (isNaN(chr3)) {
  8855. enc4 = 64;
  8856. }
  8857. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8858. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8859. }
  8860. return "data:image/png;base64," + output;
  8861. };
  8862. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8863. if (bias === void 0) { bias = null; }
  8864. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8865. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8866. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8867. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8868. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8869. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8870. }
  8871. if (bias) {
  8872. minimum.x -= minimum.x * bias.x + bias.y;
  8873. minimum.y -= minimum.y * bias.x + bias.y;
  8874. minimum.z -= minimum.z * bias.x + bias.y;
  8875. maximum.x += maximum.x * bias.x + bias.y;
  8876. maximum.y += maximum.y * bias.x + bias.y;
  8877. maximum.z += maximum.z * bias.x + bias.y;
  8878. }
  8879. return {
  8880. minimum: minimum,
  8881. maximum: maximum
  8882. };
  8883. };
  8884. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8885. if (bias === void 0) { bias = null; }
  8886. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8887. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8888. if (!stride) {
  8889. stride = 3;
  8890. }
  8891. for (var index = start; index < start + count; index++) {
  8892. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8893. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8894. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8895. }
  8896. if (bias) {
  8897. minimum.x -= minimum.x * bias.x + bias.y;
  8898. minimum.y -= minimum.y * bias.x + bias.y;
  8899. minimum.z -= minimum.z * bias.x + bias.y;
  8900. maximum.x += maximum.x * bias.x + bias.y;
  8901. maximum.y += maximum.y * bias.x + bias.y;
  8902. maximum.z += maximum.z * bias.x + bias.y;
  8903. }
  8904. return {
  8905. minimum: minimum,
  8906. maximum: maximum
  8907. };
  8908. };
  8909. Tools.Vector2ArrayFeeder = function (array) {
  8910. return function (index) {
  8911. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8912. var length = isFloatArray ? array.length / 2 : array.length;
  8913. if (index >= length) {
  8914. return null;
  8915. }
  8916. if (isFloatArray) {
  8917. var fa = array;
  8918. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8919. }
  8920. var a = array;
  8921. return a[index];
  8922. };
  8923. };
  8924. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8925. if (bias === void 0) { bias = null; }
  8926. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8927. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8928. var i = 0;
  8929. var cur = feeder(i++);
  8930. while (cur) {
  8931. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8932. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8933. cur = feeder(i++);
  8934. }
  8935. if (bias) {
  8936. minimum.x -= minimum.x * bias.x + bias.y;
  8937. minimum.y -= minimum.y * bias.x + bias.y;
  8938. maximum.x += maximum.x * bias.x + bias.y;
  8939. maximum.y += maximum.y * bias.x + bias.y;
  8940. }
  8941. return {
  8942. minimum: minimum,
  8943. maximum: maximum
  8944. };
  8945. };
  8946. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8947. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8948. return null;
  8949. return Array.isArray(obj) ? obj : [obj];
  8950. };
  8951. // Misc.
  8952. Tools.GetPointerPrefix = function () {
  8953. var eventPrefix = "pointer";
  8954. // Check if pointer events are supported
  8955. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8956. eventPrefix = "mouse";
  8957. }
  8958. return eventPrefix;
  8959. };
  8960. /**
  8961. * @param func - the function to be called
  8962. * @param requester - the object that will request the next frame. Falls back to window.
  8963. */
  8964. Tools.QueueNewFrame = function (func, requester) {
  8965. if (!Tools.IsWindowObjectExist()) {
  8966. return setTimeout(func, 16);
  8967. }
  8968. if (!requester) {
  8969. requester = window;
  8970. }
  8971. if (requester.requestAnimationFrame) {
  8972. return requester.requestAnimationFrame(func);
  8973. }
  8974. else if (requester.msRequestAnimationFrame) {
  8975. return requester.msRequestAnimationFrame(func);
  8976. }
  8977. else if (requester.webkitRequestAnimationFrame) {
  8978. return requester.webkitRequestAnimationFrame(func);
  8979. }
  8980. else if (requester.mozRequestAnimationFrame) {
  8981. return requester.mozRequestAnimationFrame(func);
  8982. }
  8983. else if (requester.oRequestAnimationFrame) {
  8984. return requester.oRequestAnimationFrame(func);
  8985. }
  8986. else {
  8987. return window.setTimeout(func, 16);
  8988. }
  8989. };
  8990. Tools.RequestFullscreen = function (element) {
  8991. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8992. if (!requestFunction)
  8993. return;
  8994. requestFunction.call(element);
  8995. };
  8996. Tools.ExitFullscreen = function () {
  8997. if (document.exitFullscreen) {
  8998. document.exitFullscreen();
  8999. }
  9000. else if (document.mozCancelFullScreen) {
  9001. document.mozCancelFullScreen();
  9002. }
  9003. else if (document.webkitCancelFullScreen) {
  9004. document.webkitCancelFullScreen();
  9005. }
  9006. else if (document.msCancelFullScreen) {
  9007. document.msCancelFullScreen();
  9008. }
  9009. };
  9010. Tools.SetCorsBehavior = function (url, element) {
  9011. if (url && url.indexOf("data:") === 0) {
  9012. return;
  9013. }
  9014. if (Tools.CorsBehavior) {
  9015. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9016. element.crossOrigin = Tools.CorsBehavior;
  9017. }
  9018. else {
  9019. var result = Tools.CorsBehavior(url);
  9020. if (result) {
  9021. element.crossOrigin = result;
  9022. }
  9023. }
  9024. }
  9025. };
  9026. // External files
  9027. Tools.CleanUrl = function (url) {
  9028. url = url.replace(/#/mg, "%23");
  9029. return url;
  9030. };
  9031. /**
  9032. * Loads an image as an HTMLImageElement.
  9033. * @param input url string, ArrayBuffer, or Blob to load
  9034. * @param onLoad callback called when the image successfully loads
  9035. * @param onError callback called when the image fails to load
  9036. * @param database database for caching
  9037. * @returns the HTMLImageElement of the loaded image
  9038. */
  9039. Tools.LoadImage = function (input, onLoad, onError, database) {
  9040. var url;
  9041. var usingObjectURL = false;
  9042. if (input instanceof ArrayBuffer) {
  9043. url = URL.createObjectURL(new Blob([input]));
  9044. usingObjectURL = true;
  9045. }
  9046. else if (input instanceof Blob) {
  9047. url = URL.createObjectURL(input);
  9048. usingObjectURL = true;
  9049. }
  9050. else {
  9051. url = Tools.CleanUrl(input);
  9052. url = Tools.PreprocessUrl(input);
  9053. }
  9054. var img = new Image();
  9055. Tools.SetCorsBehavior(url, img);
  9056. var loadHandler = function () {
  9057. if (usingObjectURL && img.src) {
  9058. URL.revokeObjectURL(img.src);
  9059. }
  9060. img.removeEventListener("load", loadHandler);
  9061. img.removeEventListener("error", errorHandler);
  9062. onLoad(img);
  9063. };
  9064. var errorHandler = function (err) {
  9065. if (usingObjectURL && img.src) {
  9066. URL.revokeObjectURL(img.src);
  9067. }
  9068. img.removeEventListener("load", loadHandler);
  9069. img.removeEventListener("error", errorHandler);
  9070. Tools.Error("Error while trying to load image: " + input);
  9071. if (onError) {
  9072. onError("Error while trying to load image: " + input, err);
  9073. }
  9074. };
  9075. img.addEventListener("load", loadHandler);
  9076. img.addEventListener("error", errorHandler);
  9077. var noIndexedDB = function () {
  9078. img.src = url;
  9079. };
  9080. var loadFromIndexedDB = function () {
  9081. if (database) {
  9082. database.loadImageFromDB(url, img);
  9083. }
  9084. };
  9085. //ANY database to do!
  9086. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9087. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9088. }
  9089. else {
  9090. if (url.indexOf("file:") !== -1) {
  9091. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9092. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9093. try {
  9094. var blobURL;
  9095. try {
  9096. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9097. }
  9098. catch (ex) {
  9099. // Chrome doesn't support oneTimeOnly parameter
  9100. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9101. }
  9102. img.src = blobURL;
  9103. usingObjectURL = true;
  9104. }
  9105. catch (e) {
  9106. img.src = "";
  9107. }
  9108. return img;
  9109. }
  9110. }
  9111. noIndexedDB();
  9112. }
  9113. return img;
  9114. };
  9115. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9116. url = Tools.CleanUrl(url);
  9117. url = Tools.PreprocessUrl(url);
  9118. // If file and file input are set
  9119. if (url.indexOf("file:") !== -1) {
  9120. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9121. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9122. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9123. }
  9124. }
  9125. var loadUrl = Tools.BaseUrl + url;
  9126. var aborted = false;
  9127. var fileRequest = {
  9128. onCompleteObservable: new BABYLON.Observable(),
  9129. abort: function () { return aborted = true; },
  9130. };
  9131. var requestFile = function () {
  9132. var request = new XMLHttpRequest();
  9133. var retryHandle = null;
  9134. fileRequest.abort = function () {
  9135. aborted = true;
  9136. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9137. request.abort();
  9138. }
  9139. if (retryHandle !== null) {
  9140. clearTimeout(retryHandle);
  9141. retryHandle = null;
  9142. }
  9143. };
  9144. var retryLoop = function (retryIndex) {
  9145. request.open('GET', loadUrl, true);
  9146. if (useArrayBuffer) {
  9147. request.responseType = "arraybuffer";
  9148. }
  9149. if (onProgress) {
  9150. request.addEventListener("progress", onProgress);
  9151. }
  9152. var onLoadEnd = function () {
  9153. request.removeEventListener("loadend", onLoadEnd);
  9154. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9155. fileRequest.onCompleteObservable.clear();
  9156. };
  9157. request.addEventListener("loadend", onLoadEnd);
  9158. var onReadyStateChange = function () {
  9159. if (aborted) {
  9160. return;
  9161. }
  9162. // In case of undefined state in some browsers.
  9163. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9164. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9165. request.removeEventListener("readystatechange", onReadyStateChange);
  9166. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9167. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9168. return;
  9169. }
  9170. var retryStrategy = Tools.DefaultRetryStrategy;
  9171. if (retryStrategy) {
  9172. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9173. if (waitTime !== -1) {
  9174. // Prevent the request from completing for retry.
  9175. request.removeEventListener("loadend", onLoadEnd);
  9176. request = new XMLHttpRequest();
  9177. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9178. return;
  9179. }
  9180. }
  9181. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9182. if (onError) {
  9183. onError(request, e);
  9184. }
  9185. else {
  9186. throw e;
  9187. }
  9188. }
  9189. };
  9190. request.addEventListener("readystatechange", onReadyStateChange);
  9191. request.send();
  9192. };
  9193. retryLoop(0);
  9194. };
  9195. // Caching all files
  9196. if (database && database.enableSceneOffline) {
  9197. var noIndexedDB_1 = function (request) {
  9198. if (request && request.status > 400) {
  9199. if (onError) {
  9200. onError(request);
  9201. }
  9202. }
  9203. else {
  9204. if (!aborted) {
  9205. requestFile();
  9206. }
  9207. }
  9208. };
  9209. var loadFromIndexedDB = function () {
  9210. // TODO: database needs to support aborting and should return a IFileRequest
  9211. if (aborted) {
  9212. return;
  9213. }
  9214. if (database) {
  9215. database.loadFileFromDB(url, function (data) {
  9216. if (!aborted) {
  9217. onSuccess(data);
  9218. }
  9219. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9220. }, onProgress ? function (event) {
  9221. if (!aborted) {
  9222. onProgress(event);
  9223. }
  9224. } : undefined, noIndexedDB_1, useArrayBuffer);
  9225. }
  9226. };
  9227. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9228. }
  9229. else {
  9230. requestFile();
  9231. }
  9232. return fileRequest;
  9233. };
  9234. /**
  9235. * Load a script (identified by an url). When the url returns, the
  9236. * content of this file is added into a new script element, attached to the DOM (body element)
  9237. */
  9238. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9239. var head = document.getElementsByTagName('head')[0];
  9240. var script = document.createElement('script');
  9241. script.type = 'text/javascript';
  9242. script.src = scriptUrl;
  9243. script.onload = function () {
  9244. if (onSuccess) {
  9245. onSuccess();
  9246. }
  9247. };
  9248. script.onerror = function (e) {
  9249. if (onError) {
  9250. onError("Unable to load script '" + scriptUrl + "'", e);
  9251. }
  9252. };
  9253. head.appendChild(script);
  9254. };
  9255. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9256. var reader = new FileReader();
  9257. var request = {
  9258. onCompleteObservable: new BABYLON.Observable(),
  9259. abort: function () { return reader.abort(); },
  9260. };
  9261. reader.onloadend = function (e) {
  9262. request.onCompleteObservable.notifyObservers(request);
  9263. };
  9264. reader.onload = function (e) {
  9265. //target doesn't have result from ts 1.3
  9266. callback(e.target['result']);
  9267. };
  9268. reader.onprogress = progressCallback;
  9269. reader.readAsDataURL(fileToLoad);
  9270. return request;
  9271. };
  9272. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9273. var reader = new FileReader();
  9274. var request = {
  9275. onCompleteObservable: new BABYLON.Observable(),
  9276. abort: function () { return reader.abort(); },
  9277. };
  9278. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9279. reader.onerror = function (e) {
  9280. Tools.Log("Error while reading file: " + fileToLoad.name);
  9281. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9282. };
  9283. reader.onload = function (e) {
  9284. //target doesn't have result from ts 1.3
  9285. callback(e.target['result']);
  9286. };
  9287. if (progressCallBack) {
  9288. reader.onprogress = progressCallBack;
  9289. }
  9290. if (!useArrayBuffer) {
  9291. // Asynchronous read
  9292. reader.readAsText(fileToLoad);
  9293. }
  9294. else {
  9295. reader.readAsArrayBuffer(fileToLoad);
  9296. }
  9297. return request;
  9298. };
  9299. //returns a downloadable url to a file content.
  9300. Tools.FileAsURL = function (content) {
  9301. var fileBlob = new Blob([content]);
  9302. var url = window.URL || window.webkitURL;
  9303. var link = url.createObjectURL(fileBlob);
  9304. return link;
  9305. };
  9306. // Misc.
  9307. Tools.Format = function (value, decimals) {
  9308. if (decimals === void 0) { decimals = 2; }
  9309. return value.toFixed(decimals);
  9310. };
  9311. Tools.CheckExtends = function (v, min, max) {
  9312. if (v.x < min.x)
  9313. min.x = v.x;
  9314. if (v.y < min.y)
  9315. min.y = v.y;
  9316. if (v.z < min.z)
  9317. min.z = v.z;
  9318. if (v.x > max.x)
  9319. max.x = v.x;
  9320. if (v.y > max.y)
  9321. max.y = v.y;
  9322. if (v.z > max.z)
  9323. max.z = v.z;
  9324. };
  9325. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9326. for (var prop in source) {
  9327. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9328. continue;
  9329. }
  9330. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9331. continue;
  9332. }
  9333. var sourceValue = source[prop];
  9334. var typeOfSourceValue = typeof sourceValue;
  9335. if (typeOfSourceValue === "function") {
  9336. continue;
  9337. }
  9338. try {
  9339. if (typeOfSourceValue === "object") {
  9340. if (sourceValue instanceof Array) {
  9341. destination[prop] = [];
  9342. if (sourceValue.length > 0) {
  9343. if (typeof sourceValue[0] == "object") {
  9344. for (var index = 0; index < sourceValue.length; index++) {
  9345. var clonedValue = cloneValue(sourceValue[index], destination);
  9346. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9347. destination[prop].push(clonedValue);
  9348. }
  9349. }
  9350. }
  9351. else {
  9352. destination[prop] = sourceValue.slice(0);
  9353. }
  9354. }
  9355. }
  9356. else {
  9357. destination[prop] = cloneValue(sourceValue, destination);
  9358. }
  9359. }
  9360. else {
  9361. destination[prop] = sourceValue;
  9362. }
  9363. }
  9364. catch (e) {
  9365. // Just ignore error (it could be because of a read-only property)
  9366. }
  9367. }
  9368. };
  9369. Tools.IsEmpty = function (obj) {
  9370. for (var i in obj) {
  9371. if (obj.hasOwnProperty(i)) {
  9372. return false;
  9373. }
  9374. }
  9375. return true;
  9376. };
  9377. Tools.RegisterTopRootEvents = function (events) {
  9378. for (var index = 0; index < events.length; index++) {
  9379. var event = events[index];
  9380. window.addEventListener(event.name, event.handler, false);
  9381. try {
  9382. if (window.parent) {
  9383. window.parent.addEventListener(event.name, event.handler, false);
  9384. }
  9385. }
  9386. catch (e) {
  9387. // Silently fails...
  9388. }
  9389. }
  9390. };
  9391. Tools.UnregisterTopRootEvents = function (events) {
  9392. for (var index = 0; index < events.length; index++) {
  9393. var event = events[index];
  9394. window.removeEventListener(event.name, event.handler);
  9395. try {
  9396. if (window.parent) {
  9397. window.parent.removeEventListener(event.name, event.handler);
  9398. }
  9399. }
  9400. catch (e) {
  9401. // Silently fails...
  9402. }
  9403. }
  9404. };
  9405. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9406. if (mimeType === void 0) { mimeType = "image/png"; }
  9407. // Read the contents of the framebuffer
  9408. var numberOfChannelsByLine = width * 4;
  9409. var halfHeight = height / 2;
  9410. //Reading datas from WebGL
  9411. var data = engine.readPixels(0, 0, width, height);
  9412. //To flip image on Y axis.
  9413. for (var i = 0; i < halfHeight; i++) {
  9414. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9415. var currentCell = j + i * numberOfChannelsByLine;
  9416. var targetLine = height - i - 1;
  9417. var targetCell = j + targetLine * numberOfChannelsByLine;
  9418. var temp = data[currentCell];
  9419. data[currentCell] = data[targetCell];
  9420. data[targetCell] = temp;
  9421. }
  9422. }
  9423. // Create a 2D canvas to store the result
  9424. if (!screenshotCanvas) {
  9425. screenshotCanvas = document.createElement('canvas');
  9426. }
  9427. screenshotCanvas.width = width;
  9428. screenshotCanvas.height = height;
  9429. var context = screenshotCanvas.getContext('2d');
  9430. if (context) {
  9431. // Copy the pixels to a 2D canvas
  9432. var imageData = context.createImageData(width, height);
  9433. var castData = (imageData.data);
  9434. castData.set(data);
  9435. context.putImageData(imageData, 0, 0);
  9436. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9437. }
  9438. };
  9439. /**
  9440. * Converts the canvas data to blob.
  9441. * This acts as a polyfill for browsers not supporting the to blob function.
  9442. * @param canvas Defines the canvas to extract the data from
  9443. * @param successCallback Defines the callback triggered once the data are available
  9444. * @param mimeType Defines the mime type of the result
  9445. */
  9446. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9447. if (mimeType === void 0) { mimeType = "image/png"; }
  9448. // We need HTMLCanvasElement.toBlob for HD screenshots
  9449. if (!canvas.toBlob) {
  9450. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9451. canvas.toBlob = function (callback, type, quality) {
  9452. var _this = this;
  9453. setTimeout(function () {
  9454. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9455. for (var i = 0; i < len; i++) {
  9456. arr[i] = binStr.charCodeAt(i);
  9457. }
  9458. callback(new Blob([arr]));
  9459. });
  9460. };
  9461. }
  9462. canvas.toBlob(function (blob) {
  9463. successCallback(blob);
  9464. }, mimeType);
  9465. };
  9466. /**
  9467. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9468. * @param successCallback Defines the callback triggered once the data are available
  9469. * @param mimeType Defines the mime type of the result
  9470. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9471. */
  9472. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9473. if (mimeType === void 0) { mimeType = "image/png"; }
  9474. if (successCallback) {
  9475. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9476. successCallback(base64Image);
  9477. }
  9478. else {
  9479. this.ToBlob(screenshotCanvas, function (blob) {
  9480. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9481. if (("download" in document.createElement("a"))) {
  9482. if (!fileName) {
  9483. var date = new Date();
  9484. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9485. fileName = "screenshot_" + stringDate + ".png";
  9486. }
  9487. Tools.Download(blob, fileName);
  9488. }
  9489. else {
  9490. var url = URL.createObjectURL(blob);
  9491. var newWindow = window.open("");
  9492. if (!newWindow)
  9493. return;
  9494. var img = newWindow.document.createElement("img");
  9495. img.onload = function () {
  9496. // no longer need to read the blob so it's revoked
  9497. URL.revokeObjectURL(url);
  9498. };
  9499. img.src = url;
  9500. newWindow.document.body.appendChild(img);
  9501. }
  9502. }, mimeType);
  9503. }
  9504. };
  9505. /**
  9506. * Downloads a blob in the browser
  9507. * @param blob defines the blob to download
  9508. * @param fileName defines the name of the downloaded file
  9509. */
  9510. Tools.Download = function (blob, fileName) {
  9511. if (navigator && navigator.msSaveBlob) {
  9512. navigator.msSaveBlob(blob, fileName);
  9513. return;
  9514. }
  9515. var url = window.URL.createObjectURL(blob);
  9516. var a = document.createElement("a");
  9517. document.body.appendChild(a);
  9518. a.style.display = "none";
  9519. a.href = url;
  9520. a.download = fileName;
  9521. a.addEventListener("click", function () {
  9522. if (a.parentElement) {
  9523. a.parentElement.removeChild(a);
  9524. }
  9525. });
  9526. a.click();
  9527. window.URL.revokeObjectURL(url);
  9528. };
  9529. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9530. if (mimeType === void 0) { mimeType = "image/png"; }
  9531. var width;
  9532. var height;
  9533. // If a precision value is specified
  9534. if (size.precision) {
  9535. width = Math.round(engine.getRenderWidth() * size.precision);
  9536. height = Math.round(width / engine.getAspectRatio(camera));
  9537. }
  9538. else if (size.width && size.height) {
  9539. width = size.width;
  9540. height = size.height;
  9541. }
  9542. //If passing only width, computing height to keep display canvas ratio.
  9543. else if (size.width && !size.height) {
  9544. width = size.width;
  9545. height = Math.round(width / engine.getAspectRatio(camera));
  9546. }
  9547. //If passing only height, computing width to keep display canvas ratio.
  9548. else if (size.height && !size.width) {
  9549. height = size.height;
  9550. width = Math.round(height * engine.getAspectRatio(camera));
  9551. }
  9552. //Assuming here that "size" parameter is a number
  9553. else if (!isNaN(size)) {
  9554. height = size;
  9555. width = size;
  9556. }
  9557. else {
  9558. Tools.Error("Invalid 'size' parameter !");
  9559. return;
  9560. }
  9561. if (!screenshotCanvas) {
  9562. screenshotCanvas = document.createElement('canvas');
  9563. }
  9564. screenshotCanvas.width = width;
  9565. screenshotCanvas.height = height;
  9566. var renderContext = screenshotCanvas.getContext("2d");
  9567. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9568. var newWidth = width;
  9569. var newHeight = newWidth / ratio;
  9570. if (newHeight > height) {
  9571. newHeight = height;
  9572. newWidth = newHeight * ratio;
  9573. }
  9574. var offsetX = Math.max(0, width - newWidth) / 2;
  9575. var offsetY = Math.max(0, height - newHeight) / 2;
  9576. var renderingCanvas = engine.getRenderingCanvas();
  9577. if (renderContext && renderingCanvas) {
  9578. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9579. }
  9580. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9581. };
  9582. /**
  9583. * Generates an image screenshot from the specified camera.
  9584. *
  9585. * @param engine The engine to use for rendering
  9586. * @param camera The camera to use for rendering
  9587. * @param size This parameter can be set to a single number or to an object with the
  9588. * following (optional) properties: precision, width, height. If a single number is passed,
  9589. * it will be used for both width and height. If an object is passed, the screenshot size
  9590. * will be derived from the parameters. The precision property is a multiplier allowing
  9591. * rendering at a higher or lower resolution.
  9592. * @param successCallback The callback receives a single parameter which contains the
  9593. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9594. * src parameter of an <img> to display it.
  9595. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9596. * Check your browser for supported MIME types.
  9597. * @param samples Texture samples (default: 1)
  9598. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9599. * @param fileName A name for for the downloaded file.
  9600. * @constructor
  9601. */
  9602. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9603. if (mimeType === void 0) { mimeType = "image/png"; }
  9604. if (samples === void 0) { samples = 1; }
  9605. if (antialiasing === void 0) { antialiasing = false; }
  9606. var width;
  9607. var height;
  9608. //If a precision value is specified
  9609. if (size.precision) {
  9610. width = Math.round(engine.getRenderWidth() * size.precision);
  9611. height = Math.round(width / engine.getAspectRatio(camera));
  9612. size = { width: width, height: height };
  9613. }
  9614. else if (size.width && size.height) {
  9615. width = size.width;
  9616. height = size.height;
  9617. }
  9618. //If passing only width, computing height to keep display canvas ratio.
  9619. else if (size.width && !size.height) {
  9620. width = size.width;
  9621. height = Math.round(width / engine.getAspectRatio(camera));
  9622. size = { width: width, height: height };
  9623. }
  9624. //If passing only height, computing width to keep display canvas ratio.
  9625. else if (size.height && !size.width) {
  9626. height = size.height;
  9627. width = Math.round(height * engine.getAspectRatio(camera));
  9628. size = { width: width, height: height };
  9629. }
  9630. //Assuming here that "size" parameter is a number
  9631. else if (!isNaN(size)) {
  9632. height = size;
  9633. width = size;
  9634. }
  9635. else {
  9636. Tools.Error("Invalid 'size' parameter !");
  9637. return;
  9638. }
  9639. var scene = camera.getScene();
  9640. var previousCamera = null;
  9641. if (scene.activeCamera !== camera) {
  9642. previousCamera = scene.activeCamera;
  9643. scene.activeCamera = camera;
  9644. }
  9645. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9646. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9647. texture.renderList = null;
  9648. texture.samples = samples;
  9649. if (antialiasing) {
  9650. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9651. }
  9652. texture.onAfterRenderObservable.add(function () {
  9653. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9654. });
  9655. scene.incrementRenderId();
  9656. scene.resetCachedMaterial();
  9657. texture.render(true);
  9658. texture.dispose();
  9659. if (previousCamera) {
  9660. scene.activeCamera = previousCamera;
  9661. }
  9662. camera.getProjectionMatrix(true); // Force cache refresh;
  9663. };
  9664. // XHR response validator for local file scenario
  9665. Tools.ValidateXHRData = function (xhr, dataType) {
  9666. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9667. if (dataType === void 0) { dataType = 7; }
  9668. try {
  9669. if (dataType & 1) {
  9670. if (xhr.responseText && xhr.responseText.length > 0) {
  9671. return true;
  9672. }
  9673. else if (dataType === 1) {
  9674. return false;
  9675. }
  9676. }
  9677. if (dataType & 2) {
  9678. // Check header width and height since there is no "TGA" magic number
  9679. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9680. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9681. return true;
  9682. }
  9683. else if (dataType === 2) {
  9684. return false;
  9685. }
  9686. }
  9687. if (dataType & 4) {
  9688. // Check for the "DDS" magic number
  9689. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9690. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9691. return true;
  9692. }
  9693. else {
  9694. return false;
  9695. }
  9696. }
  9697. }
  9698. catch (e) {
  9699. // Global protection
  9700. }
  9701. return false;
  9702. };
  9703. /**
  9704. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9705. * Be aware Math.random() could cause collisions, but:
  9706. * "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"
  9707. */
  9708. Tools.RandomId = function () {
  9709. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9710. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9711. return v.toString(16);
  9712. });
  9713. };
  9714. /**
  9715. * Test if the given uri is a base64 string.
  9716. * @param uri The uri to test
  9717. * @return True if the uri is a base64 string or false otherwise.
  9718. */
  9719. Tools.IsBase64 = function (uri) {
  9720. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9721. };
  9722. /**
  9723. * Decode the given base64 uri.
  9724. * @param uri The uri to decode
  9725. * @return The decoded base64 data.
  9726. */
  9727. Tools.DecodeBase64 = function (uri) {
  9728. var decodedString = atob(uri.split(",")[1]);
  9729. var bufferLength = decodedString.length;
  9730. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9731. for (var i = 0; i < bufferLength; i++) {
  9732. bufferView[i] = decodedString.charCodeAt(i);
  9733. }
  9734. return bufferView.buffer;
  9735. };
  9736. Object.defineProperty(Tools, "NoneLogLevel", {
  9737. get: function () {
  9738. return Tools._NoneLogLevel;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Object.defineProperty(Tools, "MessageLogLevel", {
  9744. get: function () {
  9745. return Tools._MessageLogLevel;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(Tools, "WarningLogLevel", {
  9751. get: function () {
  9752. return Tools._WarningLogLevel;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Tools, "ErrorLogLevel", {
  9758. get: function () {
  9759. return Tools._ErrorLogLevel;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. Object.defineProperty(Tools, "AllLogLevel", {
  9765. get: function () {
  9766. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9767. },
  9768. enumerable: true,
  9769. configurable: true
  9770. });
  9771. Tools._AddLogEntry = function (entry) {
  9772. Tools._LogCache = entry + Tools._LogCache;
  9773. if (Tools.OnNewCacheEntry) {
  9774. Tools.OnNewCacheEntry(entry);
  9775. }
  9776. };
  9777. Tools._FormatMessage = function (message) {
  9778. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9779. var date = new Date();
  9780. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9781. };
  9782. Tools._LogDisabled = function (message) {
  9783. // nothing to do
  9784. };
  9785. Tools._LogEnabled = function (message) {
  9786. var formattedMessage = Tools._FormatMessage(message);
  9787. console.log("BJS - " + formattedMessage);
  9788. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9789. Tools._AddLogEntry(entry);
  9790. };
  9791. Tools._WarnDisabled = function (message) {
  9792. // nothing to do
  9793. };
  9794. Tools._WarnEnabled = function (message) {
  9795. var formattedMessage = Tools._FormatMessage(message);
  9796. console.warn("BJS - " + formattedMessage);
  9797. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9798. Tools._AddLogEntry(entry);
  9799. };
  9800. Tools._ErrorDisabled = function (message) {
  9801. // nothing to do
  9802. };
  9803. Tools._ErrorEnabled = function (message) {
  9804. Tools.errorsCount++;
  9805. var formattedMessage = Tools._FormatMessage(message);
  9806. console.error("BJS - " + formattedMessage);
  9807. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9808. Tools._AddLogEntry(entry);
  9809. };
  9810. Object.defineProperty(Tools, "LogCache", {
  9811. get: function () {
  9812. return Tools._LogCache;
  9813. },
  9814. enumerable: true,
  9815. configurable: true
  9816. });
  9817. Tools.ClearLogCache = function () {
  9818. Tools._LogCache = "";
  9819. Tools.errorsCount = 0;
  9820. };
  9821. Object.defineProperty(Tools, "LogLevels", {
  9822. set: function (level) {
  9823. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9824. Tools.Log = Tools._LogEnabled;
  9825. }
  9826. else {
  9827. Tools.Log = Tools._LogDisabled;
  9828. }
  9829. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9830. Tools.Warn = Tools._WarnEnabled;
  9831. }
  9832. else {
  9833. Tools.Warn = Tools._WarnDisabled;
  9834. }
  9835. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9836. Tools.Error = Tools._ErrorEnabled;
  9837. }
  9838. else {
  9839. Tools.Error = Tools._ErrorDisabled;
  9840. }
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Tools.IsWindowObjectExist = function () {
  9846. return (typeof window) !== "undefined";
  9847. };
  9848. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9849. get: function () {
  9850. return Tools._PerformanceNoneLogLevel;
  9851. },
  9852. enumerable: true,
  9853. configurable: true
  9854. });
  9855. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9856. get: function () {
  9857. return Tools._PerformanceUserMarkLogLevel;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9863. get: function () {
  9864. return Tools._PerformanceConsoleLogLevel;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9870. set: function (level) {
  9871. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9872. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9873. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9874. return;
  9875. }
  9876. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9877. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9878. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9879. return;
  9880. }
  9881. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9882. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9888. };
  9889. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9890. };
  9891. Tools._StartUserMark = function (counterName, condition) {
  9892. if (condition === void 0) { condition = true; }
  9893. if (!Tools._performance) {
  9894. if (!Tools.IsWindowObjectExist()) {
  9895. return;
  9896. }
  9897. Tools._performance = window.performance;
  9898. }
  9899. if (!condition || !Tools._performance.mark) {
  9900. return;
  9901. }
  9902. Tools._performance.mark(counterName + "-Begin");
  9903. };
  9904. Tools._EndUserMark = function (counterName, condition) {
  9905. if (condition === void 0) { condition = true; }
  9906. if (!condition || !Tools._performance.mark) {
  9907. return;
  9908. }
  9909. Tools._performance.mark(counterName + "-End");
  9910. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9911. };
  9912. Tools._StartPerformanceConsole = function (counterName, condition) {
  9913. if (condition === void 0) { condition = true; }
  9914. if (!condition) {
  9915. return;
  9916. }
  9917. Tools._StartUserMark(counterName, condition);
  9918. if (console.time) {
  9919. console.time(counterName);
  9920. }
  9921. };
  9922. Tools._EndPerformanceConsole = function (counterName, condition) {
  9923. if (condition === void 0) { condition = true; }
  9924. if (!condition) {
  9925. return;
  9926. }
  9927. Tools._EndUserMark(counterName, condition);
  9928. if (console.time) {
  9929. console.timeEnd(counterName);
  9930. }
  9931. };
  9932. Object.defineProperty(Tools, "Now", {
  9933. get: function () {
  9934. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9935. return window.performance.now();
  9936. }
  9937. return Date.now();
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. /**
  9943. * This method will return the name of the class used to create the instance of the given object.
  9944. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9945. * @param object the object to get the class name from
  9946. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9947. */
  9948. Tools.GetClassName = function (object, isType) {
  9949. if (isType === void 0) { isType = false; }
  9950. var name = null;
  9951. if (!isType && object.getClassName) {
  9952. name = object.getClassName();
  9953. }
  9954. else {
  9955. if (object instanceof Object) {
  9956. var classObj = isType ? object : Object.getPrototypeOf(object);
  9957. name = classObj.constructor["__bjsclassName__"];
  9958. }
  9959. if (!name) {
  9960. name = typeof object;
  9961. }
  9962. }
  9963. return name;
  9964. };
  9965. Tools.First = function (array, predicate) {
  9966. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9967. var el = array_1[_i];
  9968. if (predicate(el)) {
  9969. return el;
  9970. }
  9971. }
  9972. return null;
  9973. };
  9974. /**
  9975. * This method will return the name of the full name of the class, including its owning module (if any).
  9976. * 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).
  9977. * @param object the object to get the class name from
  9978. * @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.
  9979. */
  9980. Tools.getFullClassName = function (object, isType) {
  9981. if (isType === void 0) { isType = false; }
  9982. var className = null;
  9983. var moduleName = null;
  9984. if (!isType && object.getClassName) {
  9985. className = object.getClassName();
  9986. }
  9987. else {
  9988. if (object instanceof Object) {
  9989. var classObj = isType ? object : Object.getPrototypeOf(object);
  9990. className = classObj.constructor["__bjsclassName__"];
  9991. moduleName = classObj.constructor["__bjsmoduleName__"];
  9992. }
  9993. if (!className) {
  9994. className = typeof object;
  9995. }
  9996. }
  9997. if (!className) {
  9998. return null;
  9999. }
  10000. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10001. };
  10002. /**
  10003. * 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.
  10004. * @param array
  10005. */
  10006. Tools.arrayOrStringFeeder = function (array) {
  10007. return function (index) {
  10008. if (index >= array.length) {
  10009. return null;
  10010. }
  10011. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10012. if (val && val.getHashCode) {
  10013. val = val.getHashCode();
  10014. }
  10015. if (typeof val === "string") {
  10016. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10017. }
  10018. return val;
  10019. };
  10020. };
  10021. /**
  10022. * Compute the hashCode of a stream of number
  10023. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10024. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10025. * @return the hash code computed
  10026. */
  10027. Tools.hashCodeFromStream = function (feeder) {
  10028. // Based from here: http://stackoverflow.com/a/7616484/802124
  10029. var hash = 0;
  10030. var index = 0;
  10031. var chr = feeder(index++);
  10032. while (chr != null) {
  10033. hash = ((hash << 5) - hash) + chr;
  10034. hash |= 0; // Convert to 32bit integer
  10035. chr = feeder(index++);
  10036. }
  10037. return hash;
  10038. };
  10039. /**
  10040. * Returns a promise that resolves after the given amount of time.
  10041. * @param delay Number of milliseconds to delay
  10042. * @returns Promise that resolves after the given amount of time
  10043. */
  10044. Tools.DelayAsync = function (delay) {
  10045. return new Promise(function (resolve) {
  10046. setTimeout(function () {
  10047. resolve();
  10048. }, delay);
  10049. });
  10050. };
  10051. /**
  10052. * Gets the current gradient from an array of IValueGradient
  10053. * @param ratio defines the current ratio to get
  10054. * @param gradients defines the array of IValueGradient
  10055. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10056. */
  10057. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10058. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10059. var currentGradient = gradients[gradientIndex];
  10060. var nextGradient = gradients[gradientIndex + 1];
  10061. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10062. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10063. updateFunc(currentGradient, nextGradient, scale);
  10064. }
  10065. }
  10066. };
  10067. Tools.BaseUrl = "";
  10068. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10069. /**
  10070. * Default behaviour for cors in the application.
  10071. * It can be a string if the expected behavior is identical in the entire app.
  10072. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10073. */
  10074. Tools.CorsBehavior = "anonymous";
  10075. Tools.UseFallbackTexture = true;
  10076. /**
  10077. * Use this object to register external classes like custom textures or material
  10078. * to allow the laoders to instantiate them
  10079. */
  10080. Tools.RegisteredExternalClasses = {};
  10081. // Used in case of a texture loading problem
  10082. 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";
  10083. Tools._tmpFloatArray = new Float32Array(1);
  10084. Tools.PreprocessUrl = function (url) {
  10085. return url;
  10086. };
  10087. // Logs
  10088. Tools._NoneLogLevel = 0;
  10089. Tools._MessageLogLevel = 1;
  10090. Tools._WarningLogLevel = 2;
  10091. Tools._ErrorLogLevel = 4;
  10092. Tools._LogCache = "";
  10093. Tools.errorsCount = 0;
  10094. Tools.Log = Tools._LogEnabled;
  10095. Tools.Warn = Tools._WarnEnabled;
  10096. Tools.Error = Tools._ErrorEnabled;
  10097. // Performances
  10098. Tools._PerformanceNoneLogLevel = 0;
  10099. Tools._PerformanceUserMarkLogLevel = 1;
  10100. Tools._PerformanceConsoleLogLevel = 2;
  10101. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10102. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10103. return Tools;
  10104. }());
  10105. BABYLON.Tools = Tools;
  10106. /**
  10107. * This class is used to track a performance counter which is number based.
  10108. * The user has access to many properties which give statistics of different nature
  10109. *
  10110. * The implementer can track two kinds of Performance Counter: time and count
  10111. * 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.
  10112. * 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.
  10113. */
  10114. var PerfCounter = /** @class */ (function () {
  10115. function PerfCounter() {
  10116. this._startMonitoringTime = 0;
  10117. this._min = 0;
  10118. this._max = 0;
  10119. this._average = 0;
  10120. this._lastSecAverage = 0;
  10121. this._current = 0;
  10122. this._totalValueCount = 0;
  10123. this._totalAccumulated = 0;
  10124. this._lastSecAccumulated = 0;
  10125. this._lastSecTime = 0;
  10126. this._lastSecValueCount = 0;
  10127. }
  10128. Object.defineProperty(PerfCounter.prototype, "min", {
  10129. /**
  10130. * Returns the smallest value ever
  10131. */
  10132. get: function () {
  10133. return this._min;
  10134. },
  10135. enumerable: true,
  10136. configurable: true
  10137. });
  10138. Object.defineProperty(PerfCounter.prototype, "max", {
  10139. /**
  10140. * Returns the biggest value ever
  10141. */
  10142. get: function () {
  10143. return this._max;
  10144. },
  10145. enumerable: true,
  10146. configurable: true
  10147. });
  10148. Object.defineProperty(PerfCounter.prototype, "average", {
  10149. /**
  10150. * Returns the average value since the performance counter is running
  10151. */
  10152. get: function () {
  10153. return this._average;
  10154. },
  10155. enumerable: true,
  10156. configurable: true
  10157. });
  10158. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10159. /**
  10160. * Returns the average value of the last second the counter was monitored
  10161. */
  10162. get: function () {
  10163. return this._lastSecAverage;
  10164. },
  10165. enumerable: true,
  10166. configurable: true
  10167. });
  10168. Object.defineProperty(PerfCounter.prototype, "current", {
  10169. /**
  10170. * Returns the current value
  10171. */
  10172. get: function () {
  10173. return this._current;
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(PerfCounter.prototype, "total", {
  10179. get: function () {
  10180. return this._totalAccumulated;
  10181. },
  10182. enumerable: true,
  10183. configurable: true
  10184. });
  10185. Object.defineProperty(PerfCounter.prototype, "count", {
  10186. get: function () {
  10187. return this._totalValueCount;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. /**
  10193. * Call this method to start monitoring a new frame.
  10194. * 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.
  10195. */
  10196. PerfCounter.prototype.fetchNewFrame = function () {
  10197. this._totalValueCount++;
  10198. this._current = 0;
  10199. this._lastSecValueCount++;
  10200. };
  10201. /**
  10202. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10203. * @param newCount the count value to add to the monitored count
  10204. * @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.
  10205. */
  10206. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10207. if (!PerfCounter.Enabled) {
  10208. return;
  10209. }
  10210. this._current += newCount;
  10211. if (fetchResult) {
  10212. this._fetchResult();
  10213. }
  10214. };
  10215. /**
  10216. * Start monitoring this performance counter
  10217. */
  10218. PerfCounter.prototype.beginMonitoring = function () {
  10219. if (!PerfCounter.Enabled) {
  10220. return;
  10221. }
  10222. this._startMonitoringTime = Tools.Now;
  10223. };
  10224. /**
  10225. * Compute the time lapsed since the previous beginMonitoring() call.
  10226. * @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
  10227. */
  10228. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10229. if (newFrame === void 0) { newFrame = true; }
  10230. if (!PerfCounter.Enabled) {
  10231. return;
  10232. }
  10233. if (newFrame) {
  10234. this.fetchNewFrame();
  10235. }
  10236. var currentTime = Tools.Now;
  10237. this._current = currentTime - this._startMonitoringTime;
  10238. if (newFrame) {
  10239. this._fetchResult();
  10240. }
  10241. };
  10242. PerfCounter.prototype._fetchResult = function () {
  10243. this._totalAccumulated += this._current;
  10244. this._lastSecAccumulated += this._current;
  10245. // Min/Max update
  10246. this._min = Math.min(this._min, this._current);
  10247. this._max = Math.max(this._max, this._current);
  10248. this._average = this._totalAccumulated / this._totalValueCount;
  10249. // Reset last sec?
  10250. var now = Tools.Now;
  10251. if ((now - this._lastSecTime) > 1000) {
  10252. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10253. this._lastSecTime = now;
  10254. this._lastSecAccumulated = 0;
  10255. this._lastSecValueCount = 0;
  10256. }
  10257. };
  10258. PerfCounter.Enabled = true;
  10259. return PerfCounter;
  10260. }());
  10261. BABYLON.PerfCounter = PerfCounter;
  10262. /**
  10263. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10264. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10265. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10266. * @param name The name of the class, case should be preserved
  10267. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10268. */
  10269. function className(name, module) {
  10270. return function (target) {
  10271. target["__bjsclassName__"] = name;
  10272. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10273. };
  10274. }
  10275. BABYLON.className = className;
  10276. /**
  10277. * An implementation of a loop for asynchronous functions.
  10278. */
  10279. var AsyncLoop = /** @class */ (function () {
  10280. /**
  10281. * Constroctor.
  10282. * @param iterations the number of iterations.
  10283. * @param _fn the function to run each iteration
  10284. * @param _successCallback the callback that will be called upon succesful execution
  10285. * @param offset starting offset.
  10286. */
  10287. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10288. if (offset === void 0) { offset = 0; }
  10289. this.iterations = iterations;
  10290. this._fn = _fn;
  10291. this._successCallback = _successCallback;
  10292. this.index = offset - 1;
  10293. this._done = false;
  10294. }
  10295. /**
  10296. * Execute the next iteration. Must be called after the last iteration was finished.
  10297. */
  10298. AsyncLoop.prototype.executeNext = function () {
  10299. if (!this._done) {
  10300. if (this.index + 1 < this.iterations) {
  10301. ++this.index;
  10302. this._fn(this);
  10303. }
  10304. else {
  10305. this.breakLoop();
  10306. }
  10307. }
  10308. };
  10309. /**
  10310. * Break the loop and run the success callback.
  10311. */
  10312. AsyncLoop.prototype.breakLoop = function () {
  10313. this._done = true;
  10314. this._successCallback();
  10315. };
  10316. /**
  10317. * Helper function
  10318. */
  10319. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10320. if (offset === void 0) { offset = 0; }
  10321. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10322. loop.executeNext();
  10323. return loop;
  10324. };
  10325. /**
  10326. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10327. * @param iterations total number of iterations
  10328. * @param syncedIterations number of synchronous iterations in each async iteration.
  10329. * @param fn the function to call each iteration.
  10330. * @param callback a success call back that will be called when iterating stops.
  10331. * @param breakFunction a break condition (optional)
  10332. * @param timeout timeout settings for the setTimeout function. default - 0.
  10333. * @constructor
  10334. */
  10335. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10336. if (timeout === void 0) { timeout = 0; }
  10337. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10338. if (breakFunction && breakFunction())
  10339. loop.breakLoop();
  10340. else {
  10341. setTimeout(function () {
  10342. for (var i = 0; i < syncedIterations; ++i) {
  10343. var iteration = (loop.index * syncedIterations) + i;
  10344. if (iteration >= iterations)
  10345. break;
  10346. fn(iteration);
  10347. if (breakFunction && breakFunction()) {
  10348. loop.breakLoop();
  10349. break;
  10350. }
  10351. }
  10352. loop.executeNext();
  10353. }, timeout);
  10354. }
  10355. }, callback);
  10356. };
  10357. return AsyncLoop;
  10358. }());
  10359. BABYLON.AsyncLoop = AsyncLoop;
  10360. })(BABYLON || (BABYLON = {}));
  10361. //# sourceMappingURL=babylon.tools.js.map
  10362. var BABYLON;
  10363. (function (BABYLON) {
  10364. var PromiseStates;
  10365. (function (PromiseStates) {
  10366. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10367. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10368. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10369. })(PromiseStates || (PromiseStates = {}));
  10370. var FulFillmentAgregator = /** @class */ (function () {
  10371. function FulFillmentAgregator() {
  10372. this.count = 0;
  10373. this.target = 0;
  10374. this.results = [];
  10375. }
  10376. return FulFillmentAgregator;
  10377. }());
  10378. var InternalPromise = /** @class */ (function () {
  10379. function InternalPromise(resolver) {
  10380. var _this = this;
  10381. this._state = PromiseStates.Pending;
  10382. this._children = new Array();
  10383. this._rejectWasConsumed = false;
  10384. if (!resolver) {
  10385. return;
  10386. }
  10387. try {
  10388. resolver(function (value) {
  10389. _this._resolve(value);
  10390. }, function (reason) {
  10391. _this._reject(reason);
  10392. });
  10393. }
  10394. catch (e) {
  10395. this._reject(e);
  10396. }
  10397. }
  10398. Object.defineProperty(InternalPromise.prototype, "_result", {
  10399. get: function () {
  10400. return this._resultValue;
  10401. },
  10402. set: function (value) {
  10403. this._resultValue = value;
  10404. if (this._parent && this._parent._result === undefined) {
  10405. this._parent._result = value;
  10406. }
  10407. },
  10408. enumerable: true,
  10409. configurable: true
  10410. });
  10411. InternalPromise.prototype.catch = function (onRejected) {
  10412. return this.then(undefined, onRejected);
  10413. };
  10414. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10415. var _this = this;
  10416. var newPromise = new InternalPromise();
  10417. newPromise._onFulfilled = onFulfilled;
  10418. newPromise._onRejected = onRejected;
  10419. // Composition
  10420. this._children.push(newPromise);
  10421. newPromise._parent = this;
  10422. if (this._state !== PromiseStates.Pending) {
  10423. BABYLON.Tools.SetImmediate(function () {
  10424. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10425. var returnedValue = newPromise._resolve(_this._result);
  10426. if (returnedValue !== undefined && returnedValue !== null) {
  10427. if (returnedValue._state !== undefined) {
  10428. var returnedPromise = returnedValue;
  10429. newPromise._children.push(returnedPromise);
  10430. returnedPromise._parent = newPromise;
  10431. newPromise = returnedPromise;
  10432. }
  10433. else {
  10434. newPromise._result = returnedValue;
  10435. }
  10436. }
  10437. }
  10438. else {
  10439. newPromise._reject(_this._reason);
  10440. }
  10441. });
  10442. }
  10443. return newPromise;
  10444. };
  10445. InternalPromise.prototype._moveChildren = function (children) {
  10446. var _this = this;
  10447. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10448. this._children.forEach(function (child) {
  10449. child._parent = _this;
  10450. });
  10451. if (this._state === PromiseStates.Fulfilled) {
  10452. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10453. var child = _b[_i];
  10454. child._resolve(this._result);
  10455. }
  10456. }
  10457. else if (this._state === PromiseStates.Rejected) {
  10458. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10459. var child = _d[_c];
  10460. child._reject(this._reason);
  10461. }
  10462. }
  10463. var _a;
  10464. };
  10465. InternalPromise.prototype._resolve = function (value) {
  10466. try {
  10467. this._state = PromiseStates.Fulfilled;
  10468. var returnedValue = null;
  10469. if (this._onFulfilled) {
  10470. returnedValue = this._onFulfilled(value);
  10471. }
  10472. if (returnedValue !== undefined && returnedValue !== null) {
  10473. if (returnedValue._state !== undefined) {
  10474. // Transmit children
  10475. var returnedPromise = returnedValue;
  10476. returnedPromise._parent = this;
  10477. returnedPromise._moveChildren(this._children);
  10478. value = returnedPromise._result;
  10479. }
  10480. else {
  10481. value = returnedValue;
  10482. }
  10483. }
  10484. this._result = value;
  10485. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10486. var child = _a[_i];
  10487. child._resolve(value);
  10488. }
  10489. this._children.length = 0;
  10490. delete this._onFulfilled;
  10491. delete this._onRejected;
  10492. }
  10493. catch (e) {
  10494. this._reject(e, true);
  10495. }
  10496. };
  10497. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10498. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10499. this._state = PromiseStates.Rejected;
  10500. this._reason = reason;
  10501. if (this._onRejected && !onLocalThrow) {
  10502. try {
  10503. this._onRejected(reason);
  10504. this._rejectWasConsumed = true;
  10505. }
  10506. catch (e) {
  10507. reason = e;
  10508. }
  10509. }
  10510. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10511. var child = _a[_i];
  10512. if (this._rejectWasConsumed) {
  10513. child._resolve(null);
  10514. }
  10515. else {
  10516. child._reject(reason);
  10517. }
  10518. }
  10519. this._children.length = 0;
  10520. delete this._onFulfilled;
  10521. delete this._onRejected;
  10522. };
  10523. InternalPromise.resolve = function (value) {
  10524. var newPromise = new InternalPromise();
  10525. newPromise._resolve(value);
  10526. return newPromise;
  10527. };
  10528. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10529. promise.then(function (value) {
  10530. agregator.results[index] = value;
  10531. agregator.count++;
  10532. if (agregator.count === agregator.target) {
  10533. agregator.rootPromise._resolve(agregator.results);
  10534. }
  10535. return null;
  10536. }, function (reason) {
  10537. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10538. agregator.rootPromise._reject(reason);
  10539. }
  10540. });
  10541. };
  10542. InternalPromise.all = function (promises) {
  10543. var newPromise = new InternalPromise();
  10544. var agregator = new FulFillmentAgregator();
  10545. agregator.target = promises.length;
  10546. agregator.rootPromise = newPromise;
  10547. if (promises.length) {
  10548. for (var index = 0; index < promises.length; index++) {
  10549. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10550. }
  10551. }
  10552. else {
  10553. newPromise._resolve([]);
  10554. }
  10555. return newPromise;
  10556. };
  10557. InternalPromise.race = function (promises) {
  10558. var newPromise = new InternalPromise();
  10559. if (promises.length) {
  10560. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10561. var promise = promises_1[_i];
  10562. promise.then(function (value) {
  10563. if (newPromise) {
  10564. newPromise._resolve(value);
  10565. newPromise = null;
  10566. }
  10567. return null;
  10568. }, function (reason) {
  10569. if (newPromise) {
  10570. newPromise._reject(reason);
  10571. newPromise = null;
  10572. }
  10573. });
  10574. }
  10575. }
  10576. return newPromise;
  10577. };
  10578. return InternalPromise;
  10579. }());
  10580. /**
  10581. * Helper class that provides a small promise polyfill
  10582. */
  10583. var PromisePolyfill = /** @class */ (function () {
  10584. function PromisePolyfill() {
  10585. }
  10586. /**
  10587. * Static function used to check if the polyfill is required
  10588. * If this is the case then the function will inject the polyfill to window.Promise
  10589. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10590. */
  10591. PromisePolyfill.Apply = function (force) {
  10592. if (force === void 0) { force = false; }
  10593. if (force || typeof Promise === 'undefined') {
  10594. var root = window;
  10595. root.Promise = InternalPromise;
  10596. }
  10597. };
  10598. return PromisePolyfill;
  10599. }());
  10600. BABYLON.PromisePolyfill = PromisePolyfill;
  10601. })(BABYLON || (BABYLON = {}));
  10602. //# sourceMappingURL=babylon.promise.js.map
  10603. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10604. var BABYLON;
  10605. (function (BABYLON) {
  10606. /**
  10607. * Helper class to push actions to a pool of workers.
  10608. */
  10609. var WorkerPool = /** @class */ (function () {
  10610. /**
  10611. * Constructor
  10612. * @param workers Array of workers to use for actions
  10613. */
  10614. function WorkerPool(workers) {
  10615. this._pendingActions = new Array();
  10616. this._workerInfos = workers.map(function (worker) { return ({
  10617. worker: worker,
  10618. active: false
  10619. }); });
  10620. }
  10621. /**
  10622. * Terminates all workers and clears any pending actions.
  10623. */
  10624. WorkerPool.prototype.dispose = function () {
  10625. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10626. var workerInfo = _a[_i];
  10627. workerInfo.worker.terminate();
  10628. }
  10629. delete this._workerInfos;
  10630. delete this._pendingActions;
  10631. };
  10632. /**
  10633. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10634. * pended until a worker has completed its action.
  10635. * @param action The action to perform. Call onComplete when the action is complete.
  10636. */
  10637. WorkerPool.prototype.push = function (action) {
  10638. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10639. var workerInfo = _a[_i];
  10640. if (!workerInfo.active) {
  10641. this._execute(workerInfo, action);
  10642. return;
  10643. }
  10644. }
  10645. this._pendingActions.push(action);
  10646. };
  10647. WorkerPool.prototype._execute = function (workerInfo, action) {
  10648. var _this = this;
  10649. workerInfo.active = true;
  10650. action(workerInfo.worker, function () {
  10651. workerInfo.active = false;
  10652. var nextAction = _this._pendingActions.shift();
  10653. if (nextAction) {
  10654. _this._execute(workerInfo, nextAction);
  10655. }
  10656. });
  10657. };
  10658. return WorkerPool;
  10659. }());
  10660. BABYLON.WorkerPool = WorkerPool;
  10661. })(BABYLON || (BABYLON = {}));
  10662. //# sourceMappingURL=babylon.workerPool.js.map
  10663. var BABYLON;
  10664. (function (BABYLON) {
  10665. /**
  10666. * @hidden
  10667. **/
  10668. var _AlphaState = /** @class */ (function () {
  10669. /**
  10670. * Initializes the state.
  10671. */
  10672. function _AlphaState() {
  10673. this._isAlphaBlendDirty = false;
  10674. this._isBlendFunctionParametersDirty = false;
  10675. this._isBlendEquationParametersDirty = false;
  10676. this._isBlendConstantsDirty = false;
  10677. this._alphaBlend = false;
  10678. this._blendFunctionParameters = new Array(4);
  10679. this._blendEquationParameters = new Array(2);
  10680. this._blendConstants = new Array(4);
  10681. this.reset();
  10682. }
  10683. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10684. get: function () {
  10685. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10691. get: function () {
  10692. return this._alphaBlend;
  10693. },
  10694. set: function (value) {
  10695. if (this._alphaBlend === value) {
  10696. return;
  10697. }
  10698. this._alphaBlend = value;
  10699. this._isAlphaBlendDirty = true;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10705. if (this._blendConstants[0] === r &&
  10706. this._blendConstants[1] === g &&
  10707. this._blendConstants[2] === b &&
  10708. this._blendConstants[3] === a) {
  10709. return;
  10710. }
  10711. this._blendConstants[0] = r;
  10712. this._blendConstants[1] = g;
  10713. this._blendConstants[2] = b;
  10714. this._blendConstants[3] = a;
  10715. this._isBlendConstantsDirty = true;
  10716. };
  10717. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10718. if (this._blendFunctionParameters[0] === value0 &&
  10719. this._blendFunctionParameters[1] === value1 &&
  10720. this._blendFunctionParameters[2] === value2 &&
  10721. this._blendFunctionParameters[3] === value3) {
  10722. return;
  10723. }
  10724. this._blendFunctionParameters[0] = value0;
  10725. this._blendFunctionParameters[1] = value1;
  10726. this._blendFunctionParameters[2] = value2;
  10727. this._blendFunctionParameters[3] = value3;
  10728. this._isBlendFunctionParametersDirty = true;
  10729. };
  10730. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10731. if (this._blendEquationParameters[0] === rgb &&
  10732. this._blendEquationParameters[1] === alpha) {
  10733. return;
  10734. }
  10735. this._blendEquationParameters[0] = rgb;
  10736. this._blendEquationParameters[1] = alpha;
  10737. this._isBlendEquationParametersDirty = true;
  10738. };
  10739. _AlphaState.prototype.reset = function () {
  10740. this._alphaBlend = false;
  10741. this._blendFunctionParameters[0] = null;
  10742. this._blendFunctionParameters[1] = null;
  10743. this._blendFunctionParameters[2] = null;
  10744. this._blendFunctionParameters[3] = null;
  10745. this._blendEquationParameters[0] = null;
  10746. this._blendEquationParameters[1] = null;
  10747. this._blendConstants[0] = null;
  10748. this._blendConstants[1] = null;
  10749. this._blendConstants[2] = null;
  10750. this._blendConstants[3] = null;
  10751. this._isAlphaBlendDirty = true;
  10752. this._isBlendFunctionParametersDirty = false;
  10753. this._isBlendEquationParametersDirty = false;
  10754. this._isBlendConstantsDirty = false;
  10755. };
  10756. _AlphaState.prototype.apply = function (gl) {
  10757. if (!this.isDirty) {
  10758. return;
  10759. }
  10760. // Alpha blend
  10761. if (this._isAlphaBlendDirty) {
  10762. if (this._alphaBlend) {
  10763. gl.enable(gl.BLEND);
  10764. }
  10765. else {
  10766. gl.disable(gl.BLEND);
  10767. }
  10768. this._isAlphaBlendDirty = false;
  10769. }
  10770. // Alpha function
  10771. if (this._isBlendFunctionParametersDirty) {
  10772. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10773. this._isBlendFunctionParametersDirty = false;
  10774. }
  10775. // Alpha equation
  10776. if (this._isBlendEquationParametersDirty) {
  10777. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10778. this._isBlendEquationParametersDirty = false;
  10779. }
  10780. // Constants
  10781. if (this._isBlendConstantsDirty) {
  10782. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10783. this._isBlendConstantsDirty = false;
  10784. }
  10785. };
  10786. return _AlphaState;
  10787. }());
  10788. BABYLON._AlphaState = _AlphaState;
  10789. })(BABYLON || (BABYLON = {}));
  10790. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10791. var BABYLON;
  10792. (function (BABYLON) {
  10793. /**
  10794. * @hidden
  10795. **/
  10796. var _DepthCullingState = /** @class */ (function () {
  10797. /**
  10798. * Initializes the state.
  10799. */
  10800. function _DepthCullingState() {
  10801. this._isDepthTestDirty = false;
  10802. this._isDepthMaskDirty = false;
  10803. this._isDepthFuncDirty = false;
  10804. this._isCullFaceDirty = false;
  10805. this._isCullDirty = false;
  10806. this._isZOffsetDirty = false;
  10807. this._isFrontFaceDirty = false;
  10808. this.reset();
  10809. }
  10810. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10811. get: function () {
  10812. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10813. },
  10814. enumerable: true,
  10815. configurable: true
  10816. });
  10817. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10818. get: function () {
  10819. return this._zOffset;
  10820. },
  10821. set: function (value) {
  10822. if (this._zOffset === value) {
  10823. return;
  10824. }
  10825. this._zOffset = value;
  10826. this._isZOffsetDirty = true;
  10827. },
  10828. enumerable: true,
  10829. configurable: true
  10830. });
  10831. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10832. get: function () {
  10833. return this._cullFace;
  10834. },
  10835. set: function (value) {
  10836. if (this._cullFace === value) {
  10837. return;
  10838. }
  10839. this._cullFace = value;
  10840. this._isCullFaceDirty = true;
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10846. get: function () {
  10847. return this._cull;
  10848. },
  10849. set: function (value) {
  10850. if (this._cull === value) {
  10851. return;
  10852. }
  10853. this._cull = value;
  10854. this._isCullDirty = true;
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10860. get: function () {
  10861. return this._depthFunc;
  10862. },
  10863. set: function (value) {
  10864. if (this._depthFunc === value) {
  10865. return;
  10866. }
  10867. this._depthFunc = value;
  10868. this._isDepthFuncDirty = true;
  10869. },
  10870. enumerable: true,
  10871. configurable: true
  10872. });
  10873. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10874. get: function () {
  10875. return this._depthMask;
  10876. },
  10877. set: function (value) {
  10878. if (this._depthMask === value) {
  10879. return;
  10880. }
  10881. this._depthMask = value;
  10882. this._isDepthMaskDirty = true;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10888. get: function () {
  10889. return this._depthTest;
  10890. },
  10891. set: function (value) {
  10892. if (this._depthTest === value) {
  10893. return;
  10894. }
  10895. this._depthTest = value;
  10896. this._isDepthTestDirty = true;
  10897. },
  10898. enumerable: true,
  10899. configurable: true
  10900. });
  10901. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10902. get: function () {
  10903. return this._frontFace;
  10904. },
  10905. set: function (value) {
  10906. if (this._frontFace === value) {
  10907. return;
  10908. }
  10909. this._frontFace = value;
  10910. this._isFrontFaceDirty = true;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. _DepthCullingState.prototype.reset = function () {
  10916. this._depthMask = true;
  10917. this._depthTest = true;
  10918. this._depthFunc = null;
  10919. this._cullFace = null;
  10920. this._cull = null;
  10921. this._zOffset = 0;
  10922. this._frontFace = null;
  10923. this._isDepthTestDirty = true;
  10924. this._isDepthMaskDirty = true;
  10925. this._isDepthFuncDirty = false;
  10926. this._isCullFaceDirty = false;
  10927. this._isCullDirty = false;
  10928. this._isZOffsetDirty = false;
  10929. this._isFrontFaceDirty = false;
  10930. };
  10931. _DepthCullingState.prototype.apply = function (gl) {
  10932. if (!this.isDirty) {
  10933. return;
  10934. }
  10935. // Cull
  10936. if (this._isCullDirty) {
  10937. if (this.cull) {
  10938. gl.enable(gl.CULL_FACE);
  10939. }
  10940. else {
  10941. gl.disable(gl.CULL_FACE);
  10942. }
  10943. this._isCullDirty = false;
  10944. }
  10945. // Cull face
  10946. if (this._isCullFaceDirty) {
  10947. gl.cullFace(this.cullFace);
  10948. this._isCullFaceDirty = false;
  10949. }
  10950. // Depth mask
  10951. if (this._isDepthMaskDirty) {
  10952. gl.depthMask(this.depthMask);
  10953. this._isDepthMaskDirty = false;
  10954. }
  10955. // Depth test
  10956. if (this._isDepthTestDirty) {
  10957. if (this.depthTest) {
  10958. gl.enable(gl.DEPTH_TEST);
  10959. }
  10960. else {
  10961. gl.disable(gl.DEPTH_TEST);
  10962. }
  10963. this._isDepthTestDirty = false;
  10964. }
  10965. // Depth func
  10966. if (this._isDepthFuncDirty) {
  10967. gl.depthFunc(this.depthFunc);
  10968. this._isDepthFuncDirty = false;
  10969. }
  10970. // zOffset
  10971. if (this._isZOffsetDirty) {
  10972. if (this.zOffset) {
  10973. gl.enable(gl.POLYGON_OFFSET_FILL);
  10974. gl.polygonOffset(this.zOffset, 0);
  10975. }
  10976. else {
  10977. gl.disable(gl.POLYGON_OFFSET_FILL);
  10978. }
  10979. this._isZOffsetDirty = false;
  10980. }
  10981. // Front face
  10982. if (this._isFrontFaceDirty) {
  10983. gl.frontFace(this.frontFace);
  10984. this._isFrontFaceDirty = false;
  10985. }
  10986. };
  10987. return _DepthCullingState;
  10988. }());
  10989. BABYLON._DepthCullingState = _DepthCullingState;
  10990. })(BABYLON || (BABYLON = {}));
  10991. //# sourceMappingURL=babylon.depthCullingState.js.map
  10992. var BABYLON;
  10993. (function (BABYLON) {
  10994. /**
  10995. * @hidden
  10996. **/
  10997. var _StencilState = /** @class */ (function () {
  10998. function _StencilState() {
  10999. this._isStencilTestDirty = false;
  11000. this._isStencilMaskDirty = false;
  11001. this._isStencilFuncDirty = false;
  11002. this._isStencilOpDirty = false;
  11003. this.reset();
  11004. }
  11005. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11006. get: function () {
  11007. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11013. get: function () {
  11014. return this._stencilFunc;
  11015. },
  11016. set: function (value) {
  11017. if (this._stencilFunc === value) {
  11018. return;
  11019. }
  11020. this._stencilFunc = value;
  11021. this._isStencilFuncDirty = true;
  11022. },
  11023. enumerable: true,
  11024. configurable: true
  11025. });
  11026. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11027. get: function () {
  11028. return this._stencilFuncRef;
  11029. },
  11030. set: function (value) {
  11031. if (this._stencilFuncRef === value) {
  11032. return;
  11033. }
  11034. this._stencilFuncRef = value;
  11035. this._isStencilFuncDirty = true;
  11036. },
  11037. enumerable: true,
  11038. configurable: true
  11039. });
  11040. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11041. get: function () {
  11042. return this._stencilFuncMask;
  11043. },
  11044. set: function (value) {
  11045. if (this._stencilFuncMask === value) {
  11046. return;
  11047. }
  11048. this._stencilFuncMask = value;
  11049. this._isStencilFuncDirty = true;
  11050. },
  11051. enumerable: true,
  11052. configurable: true
  11053. });
  11054. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11055. get: function () {
  11056. return this._stencilOpStencilFail;
  11057. },
  11058. set: function (value) {
  11059. if (this._stencilOpStencilFail === value) {
  11060. return;
  11061. }
  11062. this._stencilOpStencilFail = value;
  11063. this._isStencilOpDirty = true;
  11064. },
  11065. enumerable: true,
  11066. configurable: true
  11067. });
  11068. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11069. get: function () {
  11070. return this._stencilOpDepthFail;
  11071. },
  11072. set: function (value) {
  11073. if (this._stencilOpDepthFail === value) {
  11074. return;
  11075. }
  11076. this._stencilOpDepthFail = value;
  11077. this._isStencilOpDirty = true;
  11078. },
  11079. enumerable: true,
  11080. configurable: true
  11081. });
  11082. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11083. get: function () {
  11084. return this._stencilOpStencilDepthPass;
  11085. },
  11086. set: function (value) {
  11087. if (this._stencilOpStencilDepthPass === value) {
  11088. return;
  11089. }
  11090. this._stencilOpStencilDepthPass = value;
  11091. this._isStencilOpDirty = true;
  11092. },
  11093. enumerable: true,
  11094. configurable: true
  11095. });
  11096. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11097. get: function () {
  11098. return this._stencilMask;
  11099. },
  11100. set: function (value) {
  11101. if (this._stencilMask === value) {
  11102. return;
  11103. }
  11104. this._stencilMask = value;
  11105. this._isStencilMaskDirty = true;
  11106. },
  11107. enumerable: true,
  11108. configurable: true
  11109. });
  11110. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11111. get: function () {
  11112. return this._stencilTest;
  11113. },
  11114. set: function (value) {
  11115. if (this._stencilTest === value) {
  11116. return;
  11117. }
  11118. this._stencilTest = value;
  11119. this._isStencilTestDirty = true;
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. _StencilState.prototype.reset = function () {
  11125. this._stencilTest = false;
  11126. this._stencilMask = 0xFF;
  11127. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11128. this._stencilFuncRef = 1;
  11129. this._stencilFuncMask = 0xFF;
  11130. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11131. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11132. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11133. this._isStencilTestDirty = true;
  11134. this._isStencilMaskDirty = true;
  11135. this._isStencilFuncDirty = true;
  11136. this._isStencilOpDirty = true;
  11137. };
  11138. _StencilState.prototype.apply = function (gl) {
  11139. if (!this.isDirty) {
  11140. return;
  11141. }
  11142. // Stencil test
  11143. if (this._isStencilTestDirty) {
  11144. if (this.stencilTest) {
  11145. gl.enable(gl.STENCIL_TEST);
  11146. }
  11147. else {
  11148. gl.disable(gl.STENCIL_TEST);
  11149. }
  11150. this._isStencilTestDirty = false;
  11151. }
  11152. // Stencil mask
  11153. if (this._isStencilMaskDirty) {
  11154. gl.stencilMask(this.stencilMask);
  11155. this._isStencilMaskDirty = false;
  11156. }
  11157. // Stencil func
  11158. if (this._isStencilFuncDirty) {
  11159. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11160. this._isStencilFuncDirty = false;
  11161. }
  11162. // Stencil op
  11163. if (this._isStencilOpDirty) {
  11164. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11165. this._isStencilOpDirty = false;
  11166. }
  11167. };
  11168. return _StencilState;
  11169. }());
  11170. BABYLON._StencilState = _StencilState;
  11171. })(BABYLON || (BABYLON = {}));
  11172. //# sourceMappingURL=babylon.stencilState.js.map
  11173. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11174. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11175. s = arguments[i];
  11176. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11177. t[p] = s[p];
  11178. }
  11179. return t;
  11180. };
  11181. var BABYLON;
  11182. (function (BABYLON) {
  11183. /**
  11184. * Keeps track of all the buffer info used in engine.
  11185. */
  11186. var BufferPointer = /** @class */ (function () {
  11187. function BufferPointer() {
  11188. }
  11189. return BufferPointer;
  11190. }());
  11191. /**
  11192. * Interface for attribute information associated with buffer instanciation
  11193. */
  11194. var InstancingAttributeInfo = /** @class */ (function () {
  11195. function InstancingAttributeInfo() {
  11196. }
  11197. return InstancingAttributeInfo;
  11198. }());
  11199. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11200. /**
  11201. * Define options used to create a render target texture
  11202. */
  11203. var RenderTargetCreationOptions = /** @class */ (function () {
  11204. function RenderTargetCreationOptions() {
  11205. }
  11206. return RenderTargetCreationOptions;
  11207. }());
  11208. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11209. /**
  11210. * Define options used to create a depth texture
  11211. */
  11212. var DepthTextureCreationOptions = /** @class */ (function () {
  11213. function DepthTextureCreationOptions() {
  11214. }
  11215. return DepthTextureCreationOptions;
  11216. }());
  11217. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11218. /**
  11219. * Class used to describe the capabilities of the engine relatively to the current browser
  11220. */
  11221. var EngineCapabilities = /** @class */ (function () {
  11222. function EngineCapabilities() {
  11223. }
  11224. return EngineCapabilities;
  11225. }());
  11226. BABYLON.EngineCapabilities = EngineCapabilities;
  11227. /**
  11228. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11229. */
  11230. var Engine = /** @class */ (function () {
  11231. /**
  11232. * Creates a new engine
  11233. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11234. * @param antialias defines enable antialiasing (default: false)
  11235. * @param options defines further options to be sent to the getContext() function
  11236. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11237. */
  11238. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11239. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11240. var _this = this;
  11241. // Public members
  11242. /**
  11243. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11244. */
  11245. this.forcePOTTextures = false;
  11246. /**
  11247. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11248. */
  11249. this.isFullscreen = false;
  11250. /**
  11251. * Gets a boolean indicating if the pointer is currently locked
  11252. */
  11253. this.isPointerLock = false;
  11254. /**
  11255. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11256. */
  11257. this.cullBackFaces = true;
  11258. /**
  11259. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11260. */
  11261. this.renderEvenInBackground = true;
  11262. /**
  11263. * Gets or sets a boolean indicating that cache can be kept between frames
  11264. */
  11265. this.preventCacheWipeBetweenFrames = false;
  11266. /**
  11267. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11268. **/
  11269. this.enableOfflineSupport = false;
  11270. /**
  11271. * 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)
  11272. **/
  11273. this.disableManifestCheck = false;
  11274. /**
  11275. * Gets the list of created scenes
  11276. */
  11277. this.scenes = new Array();
  11278. /**
  11279. * Gets the list of created postprocesses
  11280. */
  11281. this.postProcesses = new Array();
  11282. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11283. this.validateShaderPrograms = false;
  11284. // Observables
  11285. /**
  11286. * Observable event triggered each time the rendering canvas is resized
  11287. */
  11288. this.onResizeObservable = new BABYLON.Observable();
  11289. /**
  11290. * Observable event triggered each time the canvas loses focus
  11291. */
  11292. this.onCanvasBlurObservable = new BABYLON.Observable();
  11293. /**
  11294. * Observable event triggered each time the canvas gains focus
  11295. */
  11296. this.onCanvasFocusObservable = new BABYLON.Observable();
  11297. /**
  11298. * Observable event triggered each time the canvas receives pointerout event
  11299. */
  11300. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11301. /**
  11302. * Observable event triggered before each texture is initialized
  11303. */
  11304. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11305. //WebVR
  11306. this._vrDisplay = undefined;
  11307. this._vrSupported = false;
  11308. this._vrExclusivePointerMode = false;
  11309. // Uniform buffers list
  11310. /**
  11311. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11312. */
  11313. this.disableUniformBuffers = false;
  11314. /** @hidden */
  11315. this._uniformBuffers = new Array();
  11316. // Observables
  11317. /**
  11318. * Observable raised when the engine begins a new frame
  11319. */
  11320. this.onBeginFrameObservable = new BABYLON.Observable();
  11321. /**
  11322. * Observable raised when the engine ends the current frame
  11323. */
  11324. this.onEndFrameObservable = new BABYLON.Observable();
  11325. /**
  11326. * Observable raised when the engine is about to compile a shader
  11327. */
  11328. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11329. /**
  11330. * Observable raised when the engine has jsut compiled a shader
  11331. */
  11332. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11333. this._windowIsBackground = false;
  11334. this._webGLVersion = 1.0;
  11335. /** @hidden */
  11336. this._badOS = false;
  11337. /** @hidden */
  11338. this._badDesktopOS = false;
  11339. /**
  11340. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11341. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11342. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11343. */
  11344. this.disableTextureBindingOptimization = false;
  11345. /**
  11346. * Observable signaled when VR display mode changes
  11347. */
  11348. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11349. /**
  11350. * Observable signaled when VR request present is complete
  11351. */
  11352. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11353. /**
  11354. * Observable signaled when VR request present starts
  11355. */
  11356. this.onVRRequestPresentStart = new BABYLON.Observable();
  11357. this._colorWrite = true;
  11358. /** @hidden */
  11359. this._drawCalls = new BABYLON.PerfCounter();
  11360. /** @hidden */
  11361. this._textureCollisions = new BABYLON.PerfCounter();
  11362. this._renderingQueueLaunched = false;
  11363. this._activeRenderLoops = new Array();
  11364. // Deterministic lockstepMaxSteps
  11365. this._deterministicLockstep = false;
  11366. this._lockstepMaxSteps = 4;
  11367. // Lost context
  11368. /**
  11369. * Observable signaled when a context lost event is raised
  11370. */
  11371. this.onContextLostObservable = new BABYLON.Observable();
  11372. /**
  11373. * Observable signaled when a context restored event is raised
  11374. */
  11375. this.onContextRestoredObservable = new BABYLON.Observable();
  11376. this._contextWasLost = false;
  11377. this._doNotHandleContextLost = false;
  11378. // FPS
  11379. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11380. this._fps = 60;
  11381. this._deltaTime = 0;
  11382. /**
  11383. * Turn this value on if you want to pause FPS computation when in background
  11384. */
  11385. this.disablePerformanceMonitorInBackground = false;
  11386. // States
  11387. /** @hidden */
  11388. this._depthCullingState = new BABYLON._DepthCullingState();
  11389. /** @hidden */
  11390. this._stencilState = new BABYLON._StencilState();
  11391. /** @hidden */
  11392. this._alphaState = new BABYLON._AlphaState();
  11393. /** @hidden */
  11394. this._alphaMode = Engine.ALPHA_DISABLE;
  11395. // Cache
  11396. this._internalTexturesCache = new Array();
  11397. /** @hidden */
  11398. this._activeChannel = 0;
  11399. this._currentTextureChannel = -1;
  11400. /** @hidden */
  11401. this._boundTexturesCache = {};
  11402. this._compiledEffects = {};
  11403. this._vertexAttribArraysEnabled = [];
  11404. this._uintIndicesCurrentlySet = false;
  11405. this._currentBoundBuffer = new Array();
  11406. /** @hidden */
  11407. this._currentFramebuffer = null;
  11408. this._currentBufferPointers = new Array();
  11409. this._currentInstanceLocations = new Array();
  11410. this._currentInstanceBuffers = new Array();
  11411. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11412. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11413. this._vaoRecordInProgress = false;
  11414. this._mustWipeVertexAttributes = false;
  11415. this._nextFreeTextureSlots = new Array();
  11416. this._maxSimultaneousTextures = 0;
  11417. this._activeRequests = new Array();
  11418. // Hardware supported Compressed Textures
  11419. this._texturesSupported = new Array();
  11420. /**
  11421. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11422. */
  11423. this.premultipliedAlpha = true;
  11424. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11425. this._onVRFullScreenTriggered = function () {
  11426. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11427. //get the old size before we change
  11428. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11429. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11430. //get the width and height, change the render size
  11431. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11432. _this.setHardwareScalingLevel(1);
  11433. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11434. }
  11435. else {
  11436. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11437. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11438. }
  11439. };
  11440. this._unpackFlipYCached = null;
  11441. this._boundUniforms = {};
  11442. // Register promises
  11443. BABYLON.PromisePolyfill.Apply();
  11444. var canvas = null;
  11445. Engine.Instances.push(this);
  11446. if (!canvasOrContext) {
  11447. return;
  11448. }
  11449. options = options || {};
  11450. if (canvasOrContext.getContext) {
  11451. canvas = canvasOrContext;
  11452. this._renderingCanvas = canvas;
  11453. if (antialias != null) {
  11454. options.antialias = antialias;
  11455. }
  11456. if (options.deterministicLockstep === undefined) {
  11457. options.deterministicLockstep = false;
  11458. }
  11459. if (options.lockstepMaxSteps === undefined) {
  11460. options.lockstepMaxSteps = 4;
  11461. }
  11462. if (options.preserveDrawingBuffer === undefined) {
  11463. options.preserveDrawingBuffer = false;
  11464. }
  11465. if (options.audioEngine === undefined) {
  11466. options.audioEngine = true;
  11467. }
  11468. if (options.stencil === undefined) {
  11469. options.stencil = true;
  11470. }
  11471. if (options.premultipliedAlpha === false) {
  11472. this.premultipliedAlpha = false;
  11473. }
  11474. this._deterministicLockstep = options.deterministicLockstep;
  11475. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11476. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11477. // Exceptions
  11478. if (navigator && navigator.userAgent) {
  11479. var ua = navigator.userAgent;
  11480. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11481. var exception = _a[_i];
  11482. var key = exception.key;
  11483. var targets = exception.targets;
  11484. if (ua.indexOf(key) > -1) {
  11485. if (exception.capture && exception.captureConstraint) {
  11486. var capture = exception.capture;
  11487. var constraint = exception.captureConstraint;
  11488. var regex = new RegExp(capture);
  11489. var matches = regex.exec(ua);
  11490. if (matches && matches.length > 0) {
  11491. var capturedValue = parseInt(matches[matches.length - 1]);
  11492. if (capturedValue >= constraint) {
  11493. continue;
  11494. }
  11495. }
  11496. }
  11497. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11498. var target = targets_1[_b];
  11499. switch (target) {
  11500. case "uniformBuffer":
  11501. this.disableUniformBuffers = true;
  11502. break;
  11503. case "textureBindingOptimization":
  11504. this.disableTextureBindingOptimization = true;
  11505. break;
  11506. }
  11507. }
  11508. }
  11509. }
  11510. }
  11511. // GL
  11512. if (!options.disableWebGL2Support) {
  11513. try {
  11514. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11515. if (this._gl) {
  11516. this._webGLVersion = 2.0;
  11517. }
  11518. }
  11519. catch (e) {
  11520. // Do nothing
  11521. }
  11522. }
  11523. if (!this._gl) {
  11524. if (!canvas) {
  11525. throw new Error("The provided canvas is null or undefined.");
  11526. }
  11527. try {
  11528. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11529. }
  11530. catch (e) {
  11531. throw new Error("WebGL not supported");
  11532. }
  11533. }
  11534. if (!this._gl) {
  11535. throw new Error("WebGL not supported");
  11536. }
  11537. this._onCanvasFocus = function () {
  11538. _this.onCanvasFocusObservable.notifyObservers(_this);
  11539. };
  11540. this._onCanvasBlur = function () {
  11541. _this.onCanvasBlurObservable.notifyObservers(_this);
  11542. };
  11543. canvas.addEventListener("focus", this._onCanvasFocus);
  11544. canvas.addEventListener("blur", this._onCanvasBlur);
  11545. this._onBlur = function () {
  11546. if (_this.disablePerformanceMonitorInBackground) {
  11547. _this._performanceMonitor.disable();
  11548. }
  11549. _this._windowIsBackground = true;
  11550. };
  11551. this._onFocus = function () {
  11552. if (_this.disablePerformanceMonitorInBackground) {
  11553. _this._performanceMonitor.enable();
  11554. }
  11555. _this._windowIsBackground = false;
  11556. };
  11557. this._onCanvasPointerOut = function (ev) {
  11558. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11559. };
  11560. window.addEventListener("blur", this._onBlur);
  11561. window.addEventListener("focus", this._onFocus);
  11562. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11563. // Context lost
  11564. if (!this._doNotHandleContextLost) {
  11565. this._onContextLost = function (evt) {
  11566. evt.preventDefault();
  11567. _this._contextWasLost = true;
  11568. BABYLON.Tools.Warn("WebGL context lost.");
  11569. _this.onContextLostObservable.notifyObservers(_this);
  11570. };
  11571. this._onContextRestored = function (evt) {
  11572. // Adding a timeout to avoid race condition at browser level
  11573. setTimeout(function () {
  11574. // Rebuild gl context
  11575. _this._initGLContext();
  11576. // Rebuild effects
  11577. _this._rebuildEffects();
  11578. // Rebuild textures
  11579. _this._rebuildInternalTextures();
  11580. // Rebuild buffers
  11581. _this._rebuildBuffers();
  11582. // Cache
  11583. _this.wipeCaches(true);
  11584. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11585. _this.onContextRestoredObservable.notifyObservers(_this);
  11586. _this._contextWasLost = false;
  11587. }, 0);
  11588. };
  11589. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11590. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11591. }
  11592. }
  11593. else {
  11594. this._gl = canvasOrContext;
  11595. this._renderingCanvas = this._gl.canvas;
  11596. if (this._gl.renderbufferStorageMultisample) {
  11597. this._webGLVersion = 2.0;
  11598. }
  11599. options.stencil = this._gl.getContextAttributes().stencil;
  11600. }
  11601. // Viewport
  11602. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11603. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11604. this.resize();
  11605. this._isStencilEnable = options.stencil ? true : false;
  11606. this._initGLContext();
  11607. if (canvas) {
  11608. // Fullscreen
  11609. this._onFullscreenChange = function () {
  11610. if (document.fullscreen !== undefined) {
  11611. _this.isFullscreen = document.fullscreen;
  11612. }
  11613. else if (document.mozFullScreen !== undefined) {
  11614. _this.isFullscreen = document.mozFullScreen;
  11615. }
  11616. else if (document.webkitIsFullScreen !== undefined) {
  11617. _this.isFullscreen = document.webkitIsFullScreen;
  11618. }
  11619. else if (document.msIsFullScreen !== undefined) {
  11620. _this.isFullscreen = document.msIsFullScreen;
  11621. }
  11622. // Pointer lock
  11623. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11624. canvas.requestPointerLock = canvas.requestPointerLock ||
  11625. canvas.msRequestPointerLock ||
  11626. canvas.mozRequestPointerLock ||
  11627. canvas.webkitRequestPointerLock;
  11628. if (canvas.requestPointerLock) {
  11629. canvas.requestPointerLock();
  11630. }
  11631. }
  11632. };
  11633. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11634. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11635. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11636. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11637. // Pointer lock
  11638. this._onPointerLockChange = function () {
  11639. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11640. document.webkitPointerLockElement === canvas ||
  11641. document.msPointerLockElement === canvas ||
  11642. document.pointerLockElement === canvas);
  11643. };
  11644. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11645. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11646. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11647. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11648. this._onVRDisplayPointerRestricted = function () {
  11649. if (canvas) {
  11650. canvas.requestPointerLock();
  11651. }
  11652. };
  11653. this._onVRDisplayPointerUnrestricted = function () {
  11654. document.exitPointerLock();
  11655. };
  11656. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11657. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11658. }
  11659. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11660. Engine.audioEngine = new BABYLON.AudioEngine();
  11661. }
  11662. // Prepare buffer pointers
  11663. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11664. this._currentBufferPointers[i] = new BufferPointer();
  11665. }
  11666. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11667. // Load WebVR Devices
  11668. if (options.autoEnableWebVR) {
  11669. this.initWebVR();
  11670. }
  11671. // Detect if we are running on a faulty buggy OS.
  11672. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11673. // Detect if we are running on a faulty buggy desktop OS.
  11674. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11675. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11676. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11677. }
  11678. Object.defineProperty(Engine, "LastCreatedEngine", {
  11679. /**
  11680. * Gets the latest created engine
  11681. */
  11682. get: function () {
  11683. if (Engine.Instances.length === 0) {
  11684. return null;
  11685. }
  11686. return Engine.Instances[Engine.Instances.length - 1];
  11687. },
  11688. enumerable: true,
  11689. configurable: true
  11690. });
  11691. Object.defineProperty(Engine, "LastCreatedScene", {
  11692. /**
  11693. * Gets the latest created scene
  11694. */
  11695. get: function () {
  11696. var lastCreatedEngine = Engine.LastCreatedEngine;
  11697. if (!lastCreatedEngine) {
  11698. return null;
  11699. }
  11700. if (lastCreatedEngine.scenes.length === 0) {
  11701. return null;
  11702. }
  11703. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. /**
  11709. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11710. * @param flag defines which part of the materials must be marked as dirty
  11711. * @param predicate defines a predicate used to filter which materials should be affected
  11712. */
  11713. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11714. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11715. var engine = Engine.Instances[engineIndex];
  11716. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11717. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11718. }
  11719. }
  11720. };
  11721. Object.defineProperty(Engine, "Version", {
  11722. /**
  11723. * Returns the current version of the framework
  11724. */
  11725. get: function () {
  11726. return "3.3.0-alpha.12";
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11732. /**
  11733. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11734. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11735. */
  11736. get: function () {
  11737. return this._vrExclusivePointerMode;
  11738. },
  11739. enumerable: true,
  11740. configurable: true
  11741. });
  11742. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11743. /**
  11744. * Gets a boolean indicating that the engine supports uniform buffers
  11745. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11746. */
  11747. get: function () {
  11748. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11754. /**
  11755. * Gets a boolean indicating that only power of 2 textures are supported
  11756. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11757. */
  11758. get: function () {
  11759. return this._webGLVersion < 2 || this.forcePOTTextures;
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11765. /**
  11766. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11767. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11768. */
  11769. get: function () {
  11770. return this._doNotHandleContextLost;
  11771. },
  11772. set: function (value) {
  11773. this._doNotHandleContextLost = value;
  11774. },
  11775. enumerable: true,
  11776. configurable: true
  11777. });
  11778. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11779. /**
  11780. * Gets the performance monitor attached to this engine
  11781. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11782. */
  11783. get: function () {
  11784. return this._performanceMonitor;
  11785. },
  11786. enumerable: true,
  11787. configurable: true
  11788. });
  11789. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11790. /**
  11791. * Gets the list of texture formats supported
  11792. */
  11793. get: function () {
  11794. return this._texturesSupported;
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11800. /**
  11801. * Gets the list of texture formats in use
  11802. */
  11803. get: function () {
  11804. return this._textureFormatInUse;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(Engine.prototype, "currentViewport", {
  11810. /**
  11811. * Gets the current viewport
  11812. */
  11813. get: function () {
  11814. return this._cachedViewport;
  11815. },
  11816. enumerable: true,
  11817. configurable: true
  11818. });
  11819. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11820. /**
  11821. * Gets the default empty texture
  11822. */
  11823. get: function () {
  11824. if (!this._emptyTexture) {
  11825. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11826. }
  11827. return this._emptyTexture;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11833. /**
  11834. * Gets the default empty 3D texture
  11835. */
  11836. get: function () {
  11837. if (!this._emptyTexture3D) {
  11838. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11839. }
  11840. return this._emptyTexture3D;
  11841. },
  11842. enumerable: true,
  11843. configurable: true
  11844. });
  11845. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11846. /**
  11847. * Gets the default empty cube texture
  11848. */
  11849. get: function () {
  11850. if (!this._emptyCubeTexture) {
  11851. var faceData = new Uint8Array(4);
  11852. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11853. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11854. }
  11855. return this._emptyCubeTexture;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Engine.prototype._rebuildInternalTextures = function () {
  11861. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11862. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11863. var internalTexture = currentState_1[_i];
  11864. internalTexture._rebuild();
  11865. }
  11866. };
  11867. Engine.prototype._rebuildEffects = function () {
  11868. for (var key in this._compiledEffects) {
  11869. var effect = this._compiledEffects[key];
  11870. effect._prepareEffect();
  11871. }
  11872. BABYLON.Effect.ResetCache();
  11873. };
  11874. Engine.prototype._rebuildBuffers = function () {
  11875. // Index / Vertex
  11876. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11877. var scene = _a[_i];
  11878. scene.resetCachedMaterial();
  11879. scene._rebuildGeometries();
  11880. scene._rebuildTextures();
  11881. }
  11882. // Uniforms
  11883. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11884. var uniformBuffer = _c[_b];
  11885. uniformBuffer._rebuild();
  11886. }
  11887. };
  11888. Engine.prototype._initGLContext = function () {
  11889. // Caps
  11890. this._caps = new EngineCapabilities();
  11891. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11892. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11893. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11894. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11895. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11896. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11897. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11898. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11899. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11900. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11901. // Infos
  11902. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11903. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11904. if (rendererInfo != null) {
  11905. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11906. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11907. }
  11908. if (!this._glVendor) {
  11909. this._glVendor = "Unknown vendor";
  11910. }
  11911. if (!this._glRenderer) {
  11912. this._glRenderer = "Unknown renderer";
  11913. }
  11914. // Constants
  11915. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11916. if (this._gl.RGBA16F !== 0x881A) {
  11917. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11918. }
  11919. if (this._gl.RGBA32F !== 0x8814) {
  11920. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11921. }
  11922. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11923. this._gl.DEPTH24_STENCIL8 = 35056;
  11924. }
  11925. // Extensions
  11926. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11927. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11928. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11929. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11930. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11931. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11932. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11933. 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');
  11934. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11935. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11936. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11937. this._caps.highPrecisionShaderSupported = true;
  11938. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11939. if (this._caps.timerQuery) {
  11940. if (this._webGLVersion === 1) {
  11941. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11942. }
  11943. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11944. }
  11945. // Checks if some of the format renders first to allow the use of webgl inspector.
  11946. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11947. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11948. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11949. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11950. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11951. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11952. if (this._webGLVersion > 1) {
  11953. this._gl.HALF_FLOAT_OES = 0x140B;
  11954. }
  11955. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11956. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11957. // Draw buffers
  11958. if (this._webGLVersion > 1) {
  11959. this._caps.drawBuffersExtension = true;
  11960. }
  11961. else {
  11962. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11963. if (drawBuffersExtension !== null) {
  11964. this._caps.drawBuffersExtension = true;
  11965. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11966. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11967. for (var i = 0; i < 16; i++) {
  11968. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11969. }
  11970. }
  11971. else {
  11972. this._caps.drawBuffersExtension = false;
  11973. }
  11974. }
  11975. // Depth Texture
  11976. if (this._webGLVersion > 1) {
  11977. this._caps.depthTextureExtension = true;
  11978. }
  11979. else {
  11980. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11981. if (depthTextureExtension != null) {
  11982. this._caps.depthTextureExtension = true;
  11983. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11984. }
  11985. }
  11986. // Vertex array object
  11987. if (this._webGLVersion > 1) {
  11988. this._caps.vertexArrayObject = true;
  11989. }
  11990. else {
  11991. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11992. if (vertexArrayObjectExtension != null) {
  11993. this._caps.vertexArrayObject = true;
  11994. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11995. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11996. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11997. }
  11998. else {
  11999. this._caps.vertexArrayObject = false;
  12000. }
  12001. }
  12002. // Instances count
  12003. if (this._webGLVersion > 1) {
  12004. this._caps.instancedArrays = true;
  12005. }
  12006. else {
  12007. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12008. if (instanceExtension != null) {
  12009. this._caps.instancedArrays = true;
  12010. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12011. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12012. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12013. }
  12014. else {
  12015. this._caps.instancedArrays = false;
  12016. }
  12017. }
  12018. // Intelligently add supported compressed formats in order to check for.
  12019. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12020. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12021. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12022. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12023. if (this._caps.astc)
  12024. this.texturesSupported.push('-astc.ktx');
  12025. if (this._caps.s3tc)
  12026. this.texturesSupported.push('-dxt.ktx');
  12027. if (this._caps.pvrtc)
  12028. this.texturesSupported.push('-pvrtc.ktx');
  12029. if (this._caps.etc2)
  12030. this.texturesSupported.push('-etc2.ktx');
  12031. if (this._caps.etc1)
  12032. this.texturesSupported.push('-etc1.ktx');
  12033. if (this._gl.getShaderPrecisionFormat) {
  12034. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12035. if (highp) {
  12036. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12037. }
  12038. }
  12039. // Depth buffer
  12040. this.setDepthBuffer(true);
  12041. this.setDepthFunctionToLessOrEqual();
  12042. this.setDepthWrite(true);
  12043. // Texture maps
  12044. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12045. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12046. this._nextFreeTextureSlots.push(slot);
  12047. }
  12048. };
  12049. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12050. /**
  12051. * Gets version of the current webGL context
  12052. */
  12053. get: function () {
  12054. return this._webGLVersion;
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12060. /**
  12061. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12062. */
  12063. get: function () {
  12064. return this._isStencilEnable;
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Engine.prototype._prepareWorkingCanvas = function () {
  12070. if (this._workingCanvas) {
  12071. return;
  12072. }
  12073. this._workingCanvas = document.createElement("canvas");
  12074. var context = this._workingCanvas.getContext("2d");
  12075. if (context) {
  12076. this._workingContext = context;
  12077. }
  12078. };
  12079. /**
  12080. * Reset the texture cache to empty state
  12081. */
  12082. Engine.prototype.resetTextureCache = function () {
  12083. for (var key in this._boundTexturesCache) {
  12084. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12085. continue;
  12086. }
  12087. var boundTexture = this._boundTexturesCache[key];
  12088. if (boundTexture) {
  12089. this._removeDesignatedSlot(boundTexture);
  12090. }
  12091. this._boundTexturesCache[key] = null;
  12092. }
  12093. if (!this.disableTextureBindingOptimization) {
  12094. this._nextFreeTextureSlots = [];
  12095. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12096. this._nextFreeTextureSlots.push(slot);
  12097. }
  12098. }
  12099. this._currentTextureChannel = -1;
  12100. };
  12101. /**
  12102. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12103. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12104. * @returns true if engine is in deterministic lock step mode
  12105. */
  12106. Engine.prototype.isDeterministicLockStep = function () {
  12107. return this._deterministicLockstep;
  12108. };
  12109. /**
  12110. * Gets the max steps when engine is running in deterministic lock step
  12111. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12112. * @returns the max steps
  12113. */
  12114. Engine.prototype.getLockstepMaxSteps = function () {
  12115. return this._lockstepMaxSteps;
  12116. };
  12117. /**
  12118. * Gets an object containing information about the current webGL context
  12119. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12120. */
  12121. Engine.prototype.getGlInfo = function () {
  12122. return {
  12123. vendor: this._glVendor,
  12124. renderer: this._glRenderer,
  12125. version: this._glVersion
  12126. };
  12127. };
  12128. /**
  12129. * Gets current aspect ratio
  12130. * @param camera defines the camera to use to get the aspect ratio
  12131. * @param useScreen defines if screen size must be used (or the current render target if any)
  12132. * @returns a number defining the aspect ratio
  12133. */
  12134. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12135. if (useScreen === void 0) { useScreen = false; }
  12136. var viewport = camera.viewport;
  12137. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12138. };
  12139. /**
  12140. * Gets current screen aspect ratio
  12141. * @returns a number defining the aspect ratio
  12142. */
  12143. Engine.prototype.getScreenAspectRatio = function () {
  12144. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12145. };
  12146. /**
  12147. * Gets the current render width
  12148. * @param useScreen defines if screen size must be used (or the current render target if any)
  12149. * @returns a number defining the current render width
  12150. */
  12151. Engine.prototype.getRenderWidth = function (useScreen) {
  12152. if (useScreen === void 0) { useScreen = false; }
  12153. if (!useScreen && this._currentRenderTarget) {
  12154. return this._currentRenderTarget.width;
  12155. }
  12156. return this._gl.drawingBufferWidth;
  12157. };
  12158. /**
  12159. * Gets the current render height
  12160. * @param useScreen defines if screen size must be used (or the current render target if any)
  12161. * @returns a number defining the current render height
  12162. */
  12163. Engine.prototype.getRenderHeight = function (useScreen) {
  12164. if (useScreen === void 0) { useScreen = false; }
  12165. if (!useScreen && this._currentRenderTarget) {
  12166. return this._currentRenderTarget.height;
  12167. }
  12168. return this._gl.drawingBufferHeight;
  12169. };
  12170. /**
  12171. * Gets the HTML canvas attached with the current webGL context
  12172. * @returns a HTML canvas
  12173. */
  12174. Engine.prototype.getRenderingCanvas = function () {
  12175. return this._renderingCanvas;
  12176. };
  12177. /**
  12178. * Gets the client rect of the HTML canvas attached with the current webGL context
  12179. * @returns a client rectanglee
  12180. */
  12181. Engine.prototype.getRenderingCanvasClientRect = function () {
  12182. if (!this._renderingCanvas) {
  12183. return null;
  12184. }
  12185. return this._renderingCanvas.getBoundingClientRect();
  12186. };
  12187. /**
  12188. * Defines the hardware scaling level.
  12189. * By default the hardware scaling level is computed from the window device ratio.
  12190. * 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.
  12191. * @param level defines the level to use
  12192. */
  12193. Engine.prototype.setHardwareScalingLevel = function (level) {
  12194. this._hardwareScalingLevel = level;
  12195. this.resize();
  12196. };
  12197. /**
  12198. * Gets the current hardware scaling level.
  12199. * By default the hardware scaling level is computed from the window device ratio.
  12200. * 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.
  12201. * @returns a number indicating the current hardware scaling level
  12202. */
  12203. Engine.prototype.getHardwareScalingLevel = function () {
  12204. return this._hardwareScalingLevel;
  12205. };
  12206. /**
  12207. * Gets the list of loaded textures
  12208. * @returns an array containing all loaded textures
  12209. */
  12210. Engine.prototype.getLoadedTexturesCache = function () {
  12211. return this._internalTexturesCache;
  12212. };
  12213. /**
  12214. * Gets the object containing all engine capabilities
  12215. * @returns the EngineCapabilities object
  12216. */
  12217. Engine.prototype.getCaps = function () {
  12218. return this._caps;
  12219. };
  12220. Object.defineProperty(Engine.prototype, "drawCalls", {
  12221. /** @hidden */
  12222. get: function () {
  12223. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12224. return 0;
  12225. },
  12226. enumerable: true,
  12227. configurable: true
  12228. });
  12229. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12230. /** @hidden */
  12231. get: function () {
  12232. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12233. return null;
  12234. },
  12235. enumerable: true,
  12236. configurable: true
  12237. });
  12238. /**
  12239. * Gets the current depth function
  12240. * @returns a number defining the depth function
  12241. */
  12242. Engine.prototype.getDepthFunction = function () {
  12243. return this._depthCullingState.depthFunc;
  12244. };
  12245. /**
  12246. * Sets the current depth function
  12247. * @param depthFunc defines the function to use
  12248. */
  12249. Engine.prototype.setDepthFunction = function (depthFunc) {
  12250. this._depthCullingState.depthFunc = depthFunc;
  12251. };
  12252. /**
  12253. * Sets the current depth function to GREATER
  12254. */
  12255. Engine.prototype.setDepthFunctionToGreater = function () {
  12256. this._depthCullingState.depthFunc = this._gl.GREATER;
  12257. };
  12258. /**
  12259. * Sets the current depth function to GEQUAL
  12260. */
  12261. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12262. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12263. };
  12264. /**
  12265. * Sets the current depth function to LESS
  12266. */
  12267. Engine.prototype.setDepthFunctionToLess = function () {
  12268. this._depthCullingState.depthFunc = this._gl.LESS;
  12269. };
  12270. /**
  12271. * Sets the current depth function to LEQUAL
  12272. */
  12273. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12274. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12275. };
  12276. /**
  12277. * Gets a boolean indicating if stencil buffer is enabled
  12278. * @returns the current stencil buffer state
  12279. */
  12280. Engine.prototype.getStencilBuffer = function () {
  12281. return this._stencilState.stencilTest;
  12282. };
  12283. /**
  12284. * Enable or disable the stencil buffer
  12285. * @param enable defines if the stencil buffer must be enabled or disabled
  12286. */
  12287. Engine.prototype.setStencilBuffer = function (enable) {
  12288. this._stencilState.stencilTest = enable;
  12289. };
  12290. /**
  12291. * Gets the current stencil mask
  12292. * @returns a number defining the new stencil mask to use
  12293. */
  12294. Engine.prototype.getStencilMask = function () {
  12295. return this._stencilState.stencilMask;
  12296. };
  12297. /**
  12298. * Sets the current stencil mask
  12299. * @param mask defines the new stencil mask to use
  12300. */
  12301. Engine.prototype.setStencilMask = function (mask) {
  12302. this._stencilState.stencilMask = mask;
  12303. };
  12304. /**
  12305. * Gets the current stencil function
  12306. * @returns a number defining the stencil function to use
  12307. */
  12308. Engine.prototype.getStencilFunction = function () {
  12309. return this._stencilState.stencilFunc;
  12310. };
  12311. /**
  12312. * Gets the current stencil reference value
  12313. * @returns a number defining the stencil reference value to use
  12314. */
  12315. Engine.prototype.getStencilFunctionReference = function () {
  12316. return this._stencilState.stencilFuncRef;
  12317. };
  12318. /**
  12319. * Gets the current stencil mask
  12320. * @returns a number defining the stencil mask to use
  12321. */
  12322. Engine.prototype.getStencilFunctionMask = function () {
  12323. return this._stencilState.stencilFuncMask;
  12324. };
  12325. /**
  12326. * Sets the current stencil function
  12327. * @param stencilFunc defines the new stencil function to use
  12328. */
  12329. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12330. this._stencilState.stencilFunc = stencilFunc;
  12331. };
  12332. /**
  12333. * Sets the current stencil reference
  12334. * @param reference defines the new stencil reference to use
  12335. */
  12336. Engine.prototype.setStencilFunctionReference = function (reference) {
  12337. this._stencilState.stencilFuncRef = reference;
  12338. };
  12339. /**
  12340. * Sets the current stencil mask
  12341. * @param mask defines the new stencil mask to use
  12342. */
  12343. Engine.prototype.setStencilFunctionMask = function (mask) {
  12344. this._stencilState.stencilFuncMask = mask;
  12345. };
  12346. /**
  12347. * Gets the current stencil operation when stencil fails
  12348. * @returns a number defining stencil operation to use when stencil fails
  12349. */
  12350. Engine.prototype.getStencilOperationFail = function () {
  12351. return this._stencilState.stencilOpStencilFail;
  12352. };
  12353. /**
  12354. * Gets the current stencil operation when depth fails
  12355. * @returns a number defining stencil operation to use when depth fails
  12356. */
  12357. Engine.prototype.getStencilOperationDepthFail = function () {
  12358. return this._stencilState.stencilOpDepthFail;
  12359. };
  12360. /**
  12361. * Gets the current stencil operation when stencil passes
  12362. * @returns a number defining stencil operation to use when stencil passes
  12363. */
  12364. Engine.prototype.getStencilOperationPass = function () {
  12365. return this._stencilState.stencilOpStencilDepthPass;
  12366. };
  12367. /**
  12368. * Sets the stencil operation to use when stencil fails
  12369. * @param operation defines the stencil operation to use when stencil fails
  12370. */
  12371. Engine.prototype.setStencilOperationFail = function (operation) {
  12372. this._stencilState.stencilOpStencilFail = operation;
  12373. };
  12374. /**
  12375. * Sets the stencil operation to use when depth fails
  12376. * @param operation defines the stencil operation to use when depth fails
  12377. */
  12378. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12379. this._stencilState.stencilOpDepthFail = operation;
  12380. };
  12381. /**
  12382. * Sets the stencil operation to use when stencil passes
  12383. * @param operation defines the stencil operation to use when stencil passes
  12384. */
  12385. Engine.prototype.setStencilOperationPass = function (operation) {
  12386. this._stencilState.stencilOpStencilDepthPass = operation;
  12387. };
  12388. /**
  12389. * Sets a boolean indicating if the dithering state is enabled or disabled
  12390. * @param value defines the dithering state
  12391. */
  12392. Engine.prototype.setDitheringState = function (value) {
  12393. if (value) {
  12394. this._gl.enable(this._gl.DITHER);
  12395. }
  12396. else {
  12397. this._gl.disable(this._gl.DITHER);
  12398. }
  12399. };
  12400. /**
  12401. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12402. * @param value defines the rasterizer state
  12403. */
  12404. Engine.prototype.setRasterizerState = function (value) {
  12405. if (value) {
  12406. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12407. }
  12408. else {
  12409. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12410. }
  12411. };
  12412. /**
  12413. * stop executing a render loop function and remove it from the execution array
  12414. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12415. */
  12416. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12417. if (!renderFunction) {
  12418. this._activeRenderLoops = [];
  12419. return;
  12420. }
  12421. var index = this._activeRenderLoops.indexOf(renderFunction);
  12422. if (index >= 0) {
  12423. this._activeRenderLoops.splice(index, 1);
  12424. }
  12425. };
  12426. /** @hidden */
  12427. Engine.prototype._renderLoop = function () {
  12428. if (!this._contextWasLost) {
  12429. var shouldRender = true;
  12430. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12431. shouldRender = false;
  12432. }
  12433. if (shouldRender) {
  12434. // Start new frame
  12435. this.beginFrame();
  12436. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12437. var renderFunction = this._activeRenderLoops[index];
  12438. renderFunction();
  12439. }
  12440. // Present
  12441. this.endFrame();
  12442. }
  12443. }
  12444. if (this._activeRenderLoops.length > 0) {
  12445. // Register new frame
  12446. var requester = null;
  12447. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12448. requester = this._vrDisplay;
  12449. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12450. }
  12451. else {
  12452. this._renderingQueueLaunched = false;
  12453. }
  12454. };
  12455. /**
  12456. * Register and execute a render loop. The engine can have more than one render function
  12457. * @param renderFunction defines the function to continuously execute
  12458. */
  12459. Engine.prototype.runRenderLoop = function (renderFunction) {
  12460. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12461. return;
  12462. }
  12463. this._activeRenderLoops.push(renderFunction);
  12464. if (!this._renderingQueueLaunched) {
  12465. this._renderingQueueLaunched = true;
  12466. this._bindedRenderFunction = this._renderLoop.bind(this);
  12467. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12468. }
  12469. };
  12470. /**
  12471. * Toggle full screen mode
  12472. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12473. * @param options defines an option object to be sent to the requestFullscreen function
  12474. */
  12475. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12476. if (this.isFullscreen) {
  12477. BABYLON.Tools.ExitFullscreen();
  12478. }
  12479. else {
  12480. this._pointerLockRequested = requestPointerLock;
  12481. if (this._renderingCanvas) {
  12482. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12483. }
  12484. }
  12485. };
  12486. /**
  12487. * Clear the current render buffer or the current render target (if any is set up)
  12488. * @param color defines the color to use
  12489. * @param backBuffer defines if the back buffer must be cleared
  12490. * @param depth defines if the depth buffer must be cleared
  12491. * @param stencil defines if the stencil buffer must be cleared
  12492. */
  12493. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12494. if (stencil === void 0) { stencil = false; }
  12495. this.applyStates();
  12496. var mode = 0;
  12497. if (backBuffer && color) {
  12498. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12499. mode |= this._gl.COLOR_BUFFER_BIT;
  12500. }
  12501. if (depth) {
  12502. this._gl.clearDepth(1.0);
  12503. mode |= this._gl.DEPTH_BUFFER_BIT;
  12504. }
  12505. if (stencil) {
  12506. this._gl.clearStencil(0);
  12507. mode |= this._gl.STENCIL_BUFFER_BIT;
  12508. }
  12509. this._gl.clear(mode);
  12510. };
  12511. /**
  12512. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12513. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12514. * @param y defines the y-coordinate of the corner of the clear rectangle
  12515. * @param width defines the width of the clear rectangle
  12516. * @param height defines the height of the clear rectangle
  12517. * @param clearColor defines the clear color
  12518. */
  12519. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12520. var gl = this._gl;
  12521. // Save state
  12522. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12523. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12524. // Change state
  12525. gl.enable(gl.SCISSOR_TEST);
  12526. gl.scissor(x, y, width, height);
  12527. // Clear
  12528. this.clear(clearColor, true, true, true);
  12529. // Restore state
  12530. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12531. if (curScissor === true) {
  12532. gl.enable(gl.SCISSOR_TEST);
  12533. }
  12534. else {
  12535. gl.disable(gl.SCISSOR_TEST);
  12536. }
  12537. };
  12538. /** @hidden */
  12539. Engine.prototype._viewport = function (x, y, width, height) {
  12540. if (x !== this._viewportCached.x ||
  12541. y !== this._viewportCached.y ||
  12542. width !== this._viewportCached.z ||
  12543. height !== this._viewportCached.w) {
  12544. this._viewportCached.x = x;
  12545. this._viewportCached.y = y;
  12546. this._viewportCached.z = width;
  12547. this._viewportCached.w = height;
  12548. this._gl.viewport(x, y, width, height);
  12549. }
  12550. };
  12551. /**
  12552. * Set the WebGL's viewport
  12553. * @param viewport defines the viewport element to be used
  12554. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12555. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12556. */
  12557. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12558. var width = requiredWidth || this.getRenderWidth();
  12559. var height = requiredHeight || this.getRenderHeight();
  12560. var x = viewport.x || 0;
  12561. var y = viewport.y || 0;
  12562. this._cachedViewport = viewport;
  12563. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12564. };
  12565. /**
  12566. * Directly set the WebGL Viewport
  12567. * @param x defines the x coordinate of the viewport (in screen space)
  12568. * @param y defines the y coordinate of the viewport (in screen space)
  12569. * @param width defines the width of the viewport (in screen space)
  12570. * @param height defines the height of the viewport (in screen space)
  12571. * @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
  12572. */
  12573. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12574. var currentViewport = this._cachedViewport;
  12575. this._cachedViewport = null;
  12576. this._viewport(x, y, width, height);
  12577. return currentViewport;
  12578. };
  12579. /**
  12580. * Begin a new frame
  12581. */
  12582. Engine.prototype.beginFrame = function () {
  12583. this.onBeginFrameObservable.notifyObservers(this);
  12584. this._measureFps();
  12585. };
  12586. /**
  12587. * Enf the current frame
  12588. */
  12589. Engine.prototype.endFrame = function () {
  12590. // Force a flush in case we are using a bad OS.
  12591. if (this._badOS) {
  12592. this.flushFramebuffer();
  12593. }
  12594. // Submit frame to the vr device, if enabled
  12595. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12596. // TODO: We should only submit the frame if we read frameData successfully.
  12597. this._vrDisplay.submitFrame();
  12598. }
  12599. this.onEndFrameObservable.notifyObservers(this);
  12600. };
  12601. /**
  12602. * Resize the view according to the canvas' size
  12603. */
  12604. Engine.prototype.resize = function () {
  12605. // We're not resizing the size of the canvas while in VR mode & presenting
  12606. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12607. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12608. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12609. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12610. }
  12611. };
  12612. /**
  12613. * Force a specific size of the canvas
  12614. * @param width defines the new canvas' width
  12615. * @param height defines the new canvas' height
  12616. */
  12617. Engine.prototype.setSize = function (width, height) {
  12618. if (!this._renderingCanvas) {
  12619. return;
  12620. }
  12621. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12622. return;
  12623. }
  12624. this._renderingCanvas.width = width;
  12625. this._renderingCanvas.height = height;
  12626. for (var index = 0; index < this.scenes.length; index++) {
  12627. var scene = this.scenes[index];
  12628. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12629. var cam = scene.cameras[camIndex];
  12630. cam._currentRenderId = 0;
  12631. }
  12632. }
  12633. if (this.onResizeObservable.hasObservers) {
  12634. this.onResizeObservable.notifyObservers(this);
  12635. }
  12636. };
  12637. // WebVR functions
  12638. /**
  12639. * Gets a boolean indicating if a webVR device was detected
  12640. * @returns true if a webVR device was detected
  12641. */
  12642. Engine.prototype.isVRDevicePresent = function () {
  12643. return !!this._vrDisplay;
  12644. };
  12645. /**
  12646. * Gets the current webVR device
  12647. * @returns the current webVR device (or null)
  12648. */
  12649. Engine.prototype.getVRDevice = function () {
  12650. return this._vrDisplay;
  12651. };
  12652. /**
  12653. * Initializes a webVR display and starts listening to display change events
  12654. * The onVRDisplayChangedObservable will be notified upon these changes
  12655. * @returns The onVRDisplayChangedObservable
  12656. */
  12657. Engine.prototype.initWebVR = function () {
  12658. this.initWebVRAsync();
  12659. return this.onVRDisplayChangedObservable;
  12660. };
  12661. /**
  12662. * Initializes a webVR display and starts listening to display change events
  12663. * The onVRDisplayChangedObservable will be notified upon these changes
  12664. * @returns A promise containing a VRDisplay and if vr is supported
  12665. */
  12666. Engine.prototype.initWebVRAsync = function () {
  12667. var _this = this;
  12668. var notifyObservers = function () {
  12669. var eventArgs = {
  12670. vrDisplay: _this._vrDisplay,
  12671. vrSupported: _this._vrSupported
  12672. };
  12673. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12674. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12675. };
  12676. if (!this._onVrDisplayConnect) {
  12677. this._onVrDisplayConnect = function (event) {
  12678. _this._vrDisplay = event.display;
  12679. notifyObservers();
  12680. };
  12681. this._onVrDisplayDisconnect = function () {
  12682. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12683. _this._vrDisplay = undefined;
  12684. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12685. notifyObservers();
  12686. };
  12687. this._onVrDisplayPresentChange = function () {
  12688. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12689. };
  12690. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12691. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12692. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12693. }
  12694. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12695. this._webVRInitPromise.then(notifyObservers);
  12696. return this._webVRInitPromise;
  12697. };
  12698. /**
  12699. * Call this function to switch to webVR mode
  12700. * Will do nothing if webVR is not supported or if there is no webVR device
  12701. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12702. */
  12703. Engine.prototype.enableVR = function () {
  12704. var _this = this;
  12705. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12706. var onResolved = function () {
  12707. _this.onVRRequestPresentComplete.notifyObservers(true);
  12708. _this._onVRFullScreenTriggered();
  12709. };
  12710. var onRejected = function () {
  12711. _this.onVRRequestPresentComplete.notifyObservers(false);
  12712. };
  12713. this.onVRRequestPresentStart.notifyObservers(this);
  12714. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12715. }
  12716. };
  12717. /**
  12718. * Call this function to leave webVR mode
  12719. * Will do nothing if webVR is not supported or if there is no webVR device
  12720. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12721. */
  12722. Engine.prototype.disableVR = function () {
  12723. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12724. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12725. }
  12726. };
  12727. Engine.prototype._getVRDisplaysAsync = function () {
  12728. var _this = this;
  12729. return new Promise(function (res, rej) {
  12730. if (navigator.getVRDisplays) {
  12731. navigator.getVRDisplays().then(function (devices) {
  12732. _this._vrSupported = true;
  12733. // note that devices may actually be an empty array. This is fine;
  12734. // we expect this._vrDisplay to be undefined in this case.
  12735. _this._vrDisplay = devices[0];
  12736. res({
  12737. vrDisplay: _this._vrDisplay,
  12738. vrSupported: _this._vrSupported
  12739. });
  12740. });
  12741. }
  12742. else {
  12743. _this._vrDisplay = undefined;
  12744. _this._vrSupported = false;
  12745. res({
  12746. vrDisplay: _this._vrDisplay,
  12747. vrSupported: _this._vrSupported
  12748. });
  12749. }
  12750. });
  12751. };
  12752. /**
  12753. * Binds the frame buffer to the specified texture.
  12754. * @param texture The texture to render to or null for the default canvas
  12755. * @param faceIndex The face of the texture to render to in case of cube texture
  12756. * @param requiredWidth The width of the target to render to
  12757. * @param requiredHeight The height of the target to render to
  12758. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12759. * @param depthStencilTexture The depth stencil texture to use to render
  12760. * @param lodLevel defines le lod level to bind to the frame buffer
  12761. */
  12762. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12763. if (lodLevel === void 0) { lodLevel = 0; }
  12764. if (this._currentRenderTarget) {
  12765. this.unBindFramebuffer(this._currentRenderTarget);
  12766. }
  12767. this._currentRenderTarget = texture;
  12768. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12769. var gl = this._gl;
  12770. if (texture.isCube) {
  12771. if (faceIndex === undefined) {
  12772. faceIndex = 0;
  12773. }
  12774. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12775. if (depthStencilTexture) {
  12776. if (depthStencilTexture._generateStencilBuffer) {
  12777. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12778. }
  12779. else {
  12780. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12781. }
  12782. }
  12783. }
  12784. if (this._cachedViewport && !forceFullscreenViewport) {
  12785. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12786. }
  12787. else {
  12788. if (!requiredWidth) {
  12789. requiredWidth = texture.width;
  12790. if (lodLevel) {
  12791. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12792. }
  12793. }
  12794. if (!requiredHeight) {
  12795. requiredHeight = texture.height;
  12796. if (lodLevel) {
  12797. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12798. }
  12799. }
  12800. this._viewport(0, 0, requiredWidth, requiredHeight);
  12801. }
  12802. this.wipeCaches();
  12803. };
  12804. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12805. if (this._currentFramebuffer !== framebuffer) {
  12806. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12807. this._currentFramebuffer = framebuffer;
  12808. }
  12809. };
  12810. /**
  12811. * Unbind the current render target texture from the webGL context
  12812. * @param texture defines the render target texture to unbind
  12813. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12814. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12815. */
  12816. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12817. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12818. this._currentRenderTarget = null;
  12819. // If MSAA, we need to bitblt back to main texture
  12820. var gl = this._gl;
  12821. if (texture._MSAAFramebuffer) {
  12822. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12823. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12824. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12825. }
  12826. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12827. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12828. gl.generateMipmap(gl.TEXTURE_2D);
  12829. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12830. }
  12831. if (onBeforeUnbind) {
  12832. if (texture._MSAAFramebuffer) {
  12833. // Bind the correct framebuffer
  12834. this.bindUnboundFramebuffer(texture._framebuffer);
  12835. }
  12836. onBeforeUnbind();
  12837. }
  12838. this.bindUnboundFramebuffer(null);
  12839. };
  12840. /**
  12841. * Unbind a list of render target textures from the webGL context
  12842. * This is used only when drawBuffer extension or webGL2 are active
  12843. * @param textures defines the render target textures to unbind
  12844. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12845. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12846. */
  12847. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12848. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12849. this._currentRenderTarget = null;
  12850. // If MSAA, we need to bitblt back to main texture
  12851. var gl = this._gl;
  12852. if (textures[0]._MSAAFramebuffer) {
  12853. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12854. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12855. var attachments = textures[0]._attachments;
  12856. if (!attachments) {
  12857. attachments = new Array(textures.length);
  12858. textures[0]._attachments = attachments;
  12859. }
  12860. for (var i = 0; i < textures.length; i++) {
  12861. var texture = textures[i];
  12862. for (var j = 0; j < attachments.length; j++) {
  12863. attachments[j] = gl.NONE;
  12864. }
  12865. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12866. gl.readBuffer(attachments[i]);
  12867. gl.drawBuffers(attachments);
  12868. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12869. }
  12870. for (var i = 0; i < attachments.length; i++) {
  12871. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12872. }
  12873. gl.drawBuffers(attachments);
  12874. }
  12875. for (var i = 0; i < textures.length; i++) {
  12876. var texture = textures[i];
  12877. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12878. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12879. gl.generateMipmap(gl.TEXTURE_2D);
  12880. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12881. }
  12882. }
  12883. if (onBeforeUnbind) {
  12884. if (textures[0]._MSAAFramebuffer) {
  12885. // Bind the correct framebuffer
  12886. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12887. }
  12888. onBeforeUnbind();
  12889. }
  12890. this.bindUnboundFramebuffer(null);
  12891. };
  12892. /**
  12893. * Force the mipmap generation for the given render target texture
  12894. * @param texture defines the render target texture to use
  12895. */
  12896. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12897. if (texture.generateMipMaps) {
  12898. var gl = this._gl;
  12899. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12900. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12901. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12902. }
  12903. };
  12904. /**
  12905. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12906. */
  12907. Engine.prototype.flushFramebuffer = function () {
  12908. this._gl.flush();
  12909. };
  12910. /**
  12911. * Unbind the current render target and bind the default framebuffer
  12912. */
  12913. Engine.prototype.restoreDefaultFramebuffer = function () {
  12914. if (this._currentRenderTarget) {
  12915. this.unBindFramebuffer(this._currentRenderTarget);
  12916. }
  12917. else {
  12918. this.bindUnboundFramebuffer(null);
  12919. }
  12920. if (this._cachedViewport) {
  12921. this.setViewport(this._cachedViewport);
  12922. }
  12923. this.wipeCaches();
  12924. };
  12925. // UBOs
  12926. /**
  12927. * Create an uniform buffer
  12928. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12929. * @param elements defines the content of the uniform buffer
  12930. * @returns the webGL uniform buffer
  12931. */
  12932. Engine.prototype.createUniformBuffer = function (elements) {
  12933. var ubo = this._gl.createBuffer();
  12934. if (!ubo) {
  12935. throw new Error("Unable to create uniform buffer");
  12936. }
  12937. this.bindUniformBuffer(ubo);
  12938. if (elements instanceof Float32Array) {
  12939. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12940. }
  12941. else {
  12942. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12943. }
  12944. this.bindUniformBuffer(null);
  12945. ubo.references = 1;
  12946. return ubo;
  12947. };
  12948. /**
  12949. * Create a dynamic uniform buffer
  12950. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12951. * @param elements defines the content of the uniform buffer
  12952. * @returns the webGL uniform buffer
  12953. */
  12954. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12955. var ubo = this._gl.createBuffer();
  12956. if (!ubo) {
  12957. throw new Error("Unable to create dynamic uniform buffer");
  12958. }
  12959. this.bindUniformBuffer(ubo);
  12960. if (elements instanceof Float32Array) {
  12961. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12962. }
  12963. else {
  12964. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12965. }
  12966. this.bindUniformBuffer(null);
  12967. ubo.references = 1;
  12968. return ubo;
  12969. };
  12970. /**
  12971. * Update an existing uniform buffer
  12972. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12973. * @param uniformBuffer defines the target uniform buffer
  12974. * @param elements defines the content to update
  12975. * @param offset defines the offset in the uniform buffer where update should start
  12976. * @param count defines the size of the data to update
  12977. */
  12978. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12979. this.bindUniformBuffer(uniformBuffer);
  12980. if (offset === undefined) {
  12981. offset = 0;
  12982. }
  12983. if (count === undefined) {
  12984. if (elements instanceof Float32Array) {
  12985. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12986. }
  12987. else {
  12988. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12989. }
  12990. }
  12991. else {
  12992. if (elements instanceof Float32Array) {
  12993. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12994. }
  12995. else {
  12996. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12997. }
  12998. }
  12999. this.bindUniformBuffer(null);
  13000. };
  13001. // VBOs
  13002. Engine.prototype._resetVertexBufferBinding = function () {
  13003. this.bindArrayBuffer(null);
  13004. this._cachedVertexBuffers = null;
  13005. };
  13006. /**
  13007. * Creates a vertex buffer
  13008. * @param data the data for the vertex buffer
  13009. * @returns the new WebGL static buffer
  13010. */
  13011. Engine.prototype.createVertexBuffer = function (data) {
  13012. var vbo = this._gl.createBuffer();
  13013. if (!vbo) {
  13014. throw new Error("Unable to create vertex buffer");
  13015. }
  13016. this.bindArrayBuffer(vbo);
  13017. if (data instanceof Array) {
  13018. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13019. }
  13020. else {
  13021. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13022. }
  13023. this._resetVertexBufferBinding();
  13024. vbo.references = 1;
  13025. return vbo;
  13026. };
  13027. /**
  13028. * Creates a dynamic vertex buffer
  13029. * @param data the data for the dynamic vertex buffer
  13030. * @returns the new WebGL dynamic buffer
  13031. */
  13032. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13033. var vbo = this._gl.createBuffer();
  13034. if (!vbo) {
  13035. throw new Error("Unable to create dynamic vertex buffer");
  13036. }
  13037. this.bindArrayBuffer(vbo);
  13038. if (data instanceof Array) {
  13039. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13040. }
  13041. else {
  13042. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13043. }
  13044. this._resetVertexBufferBinding();
  13045. vbo.references = 1;
  13046. return vbo;
  13047. };
  13048. /**
  13049. * Update a dynamic index buffer
  13050. * @param indexBuffer defines the target index buffer
  13051. * @param indices defines the data to update
  13052. * @param offset defines the offset in the target index buffer where update should start
  13053. */
  13054. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13055. if (offset === void 0) { offset = 0; }
  13056. // Force cache update
  13057. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13058. this.bindIndexBuffer(indexBuffer);
  13059. var arrayBuffer;
  13060. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13061. arrayBuffer = indices;
  13062. }
  13063. else {
  13064. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13065. }
  13066. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13067. this._resetIndexBufferBinding();
  13068. };
  13069. /**
  13070. * Updates a dynamic vertex buffer.
  13071. * @param vertexBuffer the vertex buffer to update
  13072. * @param data the data used to update the vertex buffer
  13073. * @param byteOffset the byte offset of the data
  13074. * @param byteLength the byte length of the data
  13075. */
  13076. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13077. this.bindArrayBuffer(vertexBuffer);
  13078. if (byteOffset === undefined) {
  13079. byteOffset = 0;
  13080. }
  13081. if (byteLength === undefined) {
  13082. if (data instanceof Array) {
  13083. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13084. }
  13085. else {
  13086. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13087. }
  13088. }
  13089. else {
  13090. if (data instanceof Array) {
  13091. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13092. }
  13093. else {
  13094. if (data instanceof ArrayBuffer) {
  13095. data = new Uint8Array(data, byteOffset, byteLength);
  13096. }
  13097. else {
  13098. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13099. }
  13100. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13101. }
  13102. }
  13103. this._resetVertexBufferBinding();
  13104. };
  13105. Engine.prototype._resetIndexBufferBinding = function () {
  13106. this.bindIndexBuffer(null);
  13107. this._cachedIndexBuffer = null;
  13108. };
  13109. /**
  13110. * Creates a new index buffer
  13111. * @param indices defines the content of the index buffer
  13112. * @param updatable defines if the index buffer must be updatable
  13113. * @returns a new webGL buffer
  13114. */
  13115. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13116. var vbo = this._gl.createBuffer();
  13117. if (!vbo) {
  13118. throw new Error("Unable to create index buffer");
  13119. }
  13120. this.bindIndexBuffer(vbo);
  13121. // Check for 32 bits indices
  13122. var arrayBuffer;
  13123. var need32Bits = false;
  13124. if (indices instanceof Uint16Array) {
  13125. arrayBuffer = indices;
  13126. }
  13127. else {
  13128. //check 32 bit support
  13129. if (this._caps.uintIndices) {
  13130. if (indices instanceof Uint32Array) {
  13131. arrayBuffer = indices;
  13132. need32Bits = true;
  13133. }
  13134. else {
  13135. //number[] or Int32Array, check if 32 bit is necessary
  13136. for (var index = 0; index < indices.length; index++) {
  13137. if (indices[index] > 65535) {
  13138. need32Bits = true;
  13139. break;
  13140. }
  13141. }
  13142. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13143. }
  13144. }
  13145. else {
  13146. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13147. arrayBuffer = new Uint16Array(indices);
  13148. }
  13149. }
  13150. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13151. this._resetIndexBufferBinding();
  13152. vbo.references = 1;
  13153. vbo.is32Bits = need32Bits;
  13154. return vbo;
  13155. };
  13156. /**
  13157. * Bind a webGL buffer to the webGL context
  13158. * @param buffer defines the buffer to bind
  13159. */
  13160. Engine.prototype.bindArrayBuffer = function (buffer) {
  13161. if (!this._vaoRecordInProgress) {
  13162. this._unbindVertexArrayObject();
  13163. }
  13164. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13165. };
  13166. /**
  13167. * Bind an uniform buffer to the current webGL context
  13168. * @param buffer defines the buffer to bind
  13169. */
  13170. Engine.prototype.bindUniformBuffer = function (buffer) {
  13171. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13172. };
  13173. /**
  13174. * Bind a buffer to the current webGL context at a given location
  13175. * @param buffer defines the buffer to bind
  13176. * @param location defines the index where to bind the buffer
  13177. */
  13178. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13179. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13180. };
  13181. /**
  13182. * Bind a specific block at a given index in a specific shader program
  13183. * @param shaderProgram defines the shader program
  13184. * @param blockName defines the block name
  13185. * @param index defines the index where to bind the block
  13186. */
  13187. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13188. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13189. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13190. };
  13191. ;
  13192. Engine.prototype.bindIndexBuffer = function (buffer) {
  13193. if (!this._vaoRecordInProgress) {
  13194. this._unbindVertexArrayObject();
  13195. }
  13196. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13197. };
  13198. Engine.prototype.bindBuffer = function (buffer, target) {
  13199. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13200. this._gl.bindBuffer(target, buffer);
  13201. this._currentBoundBuffer[target] = buffer;
  13202. }
  13203. };
  13204. /**
  13205. * update the bound buffer with the given data
  13206. * @param data defines the data to update
  13207. */
  13208. Engine.prototype.updateArrayBuffer = function (data) {
  13209. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13210. };
  13211. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13212. var pointer = this._currentBufferPointers[indx];
  13213. var changed = false;
  13214. if (!pointer.active) {
  13215. changed = true;
  13216. pointer.active = true;
  13217. pointer.index = indx;
  13218. pointer.size = size;
  13219. pointer.type = type;
  13220. pointer.normalized = normalized;
  13221. pointer.stride = stride;
  13222. pointer.offset = offset;
  13223. pointer.buffer = buffer;
  13224. }
  13225. else {
  13226. if (pointer.buffer !== buffer) {
  13227. pointer.buffer = buffer;
  13228. changed = true;
  13229. }
  13230. if (pointer.size !== size) {
  13231. pointer.size = size;
  13232. changed = true;
  13233. }
  13234. if (pointer.type !== type) {
  13235. pointer.type = type;
  13236. changed = true;
  13237. }
  13238. if (pointer.normalized !== normalized) {
  13239. pointer.normalized = normalized;
  13240. changed = true;
  13241. }
  13242. if (pointer.stride !== stride) {
  13243. pointer.stride = stride;
  13244. changed = true;
  13245. }
  13246. if (pointer.offset !== offset) {
  13247. pointer.offset = offset;
  13248. changed = true;
  13249. }
  13250. }
  13251. if (changed || this._vaoRecordInProgress) {
  13252. this.bindArrayBuffer(buffer);
  13253. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13254. }
  13255. };
  13256. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13257. if (indexBuffer == null) {
  13258. return;
  13259. }
  13260. if (this._cachedIndexBuffer !== indexBuffer) {
  13261. this._cachedIndexBuffer = indexBuffer;
  13262. this.bindIndexBuffer(indexBuffer);
  13263. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13264. }
  13265. };
  13266. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13267. var attributes = effect.getAttributesNames();
  13268. if (!this._vaoRecordInProgress) {
  13269. this._unbindVertexArrayObject();
  13270. }
  13271. this.unbindAllAttributes();
  13272. for (var index = 0; index < attributes.length; index++) {
  13273. var order = effect.getAttributeLocation(index);
  13274. if (order >= 0) {
  13275. var vertexBuffer = vertexBuffers[attributes[index]];
  13276. if (!vertexBuffer) {
  13277. continue;
  13278. }
  13279. this._gl.enableVertexAttribArray(order);
  13280. if (!this._vaoRecordInProgress) {
  13281. this._vertexAttribArraysEnabled[order] = true;
  13282. }
  13283. var buffer = vertexBuffer.getBuffer();
  13284. if (buffer) {
  13285. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13286. if (vertexBuffer.getIsInstanced()) {
  13287. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13288. if (!this._vaoRecordInProgress) {
  13289. this._currentInstanceLocations.push(order);
  13290. this._currentInstanceBuffers.push(buffer);
  13291. }
  13292. }
  13293. }
  13294. }
  13295. }
  13296. };
  13297. /**
  13298. * Records a vertex array object
  13299. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13300. * @param vertexBuffers defines the list of vertex buffers to store
  13301. * @param indexBuffer defines the index buffer to store
  13302. * @param effect defines the effect to store
  13303. * @returns the new vertex array object
  13304. */
  13305. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13306. var vao = this._gl.createVertexArray();
  13307. this._vaoRecordInProgress = true;
  13308. this._gl.bindVertexArray(vao);
  13309. this._mustWipeVertexAttributes = true;
  13310. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13311. this.bindIndexBuffer(indexBuffer);
  13312. this._vaoRecordInProgress = false;
  13313. this._gl.bindVertexArray(null);
  13314. return vao;
  13315. };
  13316. /**
  13317. * Bind a specific vertex array object
  13318. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13319. * @param vertexArrayObject defines the vertex array object to bind
  13320. * @param indexBuffer defines the index buffer to bind
  13321. */
  13322. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13323. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13324. this._cachedVertexArrayObject = vertexArrayObject;
  13325. this._gl.bindVertexArray(vertexArrayObject);
  13326. this._cachedVertexBuffers = null;
  13327. this._cachedIndexBuffer = null;
  13328. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13329. this._mustWipeVertexAttributes = true;
  13330. }
  13331. };
  13332. /**
  13333. * Bind webGl buffers directly to the webGL context
  13334. * @param vertexBuffer defines the vertex buffer to bind
  13335. * @param indexBuffer defines the index buffer to bind
  13336. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13337. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13338. * @param effect defines the effect associated with the vertex buffer
  13339. */
  13340. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13341. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13342. this._cachedVertexBuffers = vertexBuffer;
  13343. this._cachedEffectForVertexBuffers = effect;
  13344. var attributesCount = effect.getAttributesCount();
  13345. this._unbindVertexArrayObject();
  13346. this.unbindAllAttributes();
  13347. var offset = 0;
  13348. for (var index = 0; index < attributesCount; index++) {
  13349. if (index < vertexDeclaration.length) {
  13350. var order = effect.getAttributeLocation(index);
  13351. if (order >= 0) {
  13352. this._gl.enableVertexAttribArray(order);
  13353. this._vertexAttribArraysEnabled[order] = true;
  13354. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13355. }
  13356. offset += vertexDeclaration[index] * 4;
  13357. }
  13358. }
  13359. }
  13360. this._bindIndexBufferWithCache(indexBuffer);
  13361. };
  13362. Engine.prototype._unbindVertexArrayObject = function () {
  13363. if (!this._cachedVertexArrayObject) {
  13364. return;
  13365. }
  13366. this._cachedVertexArrayObject = null;
  13367. this._gl.bindVertexArray(null);
  13368. };
  13369. /**
  13370. * Bind a list of vertex buffers to the webGL context
  13371. * @param vertexBuffers defines the list of vertex buffers to bind
  13372. * @param indexBuffer defines the index buffer to bind
  13373. * @param effect defines the effect associated with the vertex buffers
  13374. */
  13375. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13376. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13377. this._cachedVertexBuffers = vertexBuffers;
  13378. this._cachedEffectForVertexBuffers = effect;
  13379. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13380. }
  13381. this._bindIndexBufferWithCache(indexBuffer);
  13382. };
  13383. /**
  13384. * Unbind all instance attributes
  13385. */
  13386. Engine.prototype.unbindInstanceAttributes = function () {
  13387. var boundBuffer;
  13388. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13389. var instancesBuffer = this._currentInstanceBuffers[i];
  13390. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13391. boundBuffer = instancesBuffer;
  13392. this.bindArrayBuffer(instancesBuffer);
  13393. }
  13394. var offsetLocation = this._currentInstanceLocations[i];
  13395. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13396. }
  13397. this._currentInstanceBuffers.length = 0;
  13398. this._currentInstanceLocations.length = 0;
  13399. };
  13400. /**
  13401. * Release and free the memory of a vertex array object
  13402. * @param vao defines the vertex array object to delete
  13403. */
  13404. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13405. this._gl.deleteVertexArray(vao);
  13406. };
  13407. /** @hidden */
  13408. Engine.prototype._releaseBuffer = function (buffer) {
  13409. buffer.references--;
  13410. if (buffer.references === 0) {
  13411. this._gl.deleteBuffer(buffer);
  13412. return true;
  13413. }
  13414. return false;
  13415. };
  13416. /**
  13417. * Creates a webGL buffer to use with instanciation
  13418. * @param capacity defines the size of the buffer
  13419. * @returns the webGL buffer
  13420. */
  13421. Engine.prototype.createInstancesBuffer = function (capacity) {
  13422. var buffer = this._gl.createBuffer();
  13423. if (!buffer) {
  13424. throw new Error("Unable to create instance buffer");
  13425. }
  13426. buffer.capacity = capacity;
  13427. this.bindArrayBuffer(buffer);
  13428. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13429. return buffer;
  13430. };
  13431. /**
  13432. * Delete a webGL buffer used with instanciation
  13433. * @param buffer defines the webGL buffer to delete
  13434. */
  13435. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13436. this._gl.deleteBuffer(buffer);
  13437. };
  13438. /**
  13439. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13440. * @param instancesBuffer defines the webGL buffer to update and bind
  13441. * @param data defines the data to store in the buffer
  13442. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13443. */
  13444. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13445. this.bindArrayBuffer(instancesBuffer);
  13446. if (data) {
  13447. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13448. }
  13449. if (offsetLocations[0].index !== undefined) {
  13450. var stride = 0;
  13451. for (var i = 0; i < offsetLocations.length; i++) {
  13452. var ai = offsetLocations[i];
  13453. stride += ai.attributeSize * 4;
  13454. }
  13455. for (var i = 0; i < offsetLocations.length; i++) {
  13456. var ai = offsetLocations[i];
  13457. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13458. this._gl.enableVertexAttribArray(ai.index);
  13459. this._vertexAttribArraysEnabled[ai.index] = true;
  13460. }
  13461. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13462. this._gl.vertexAttribDivisor(ai.index, 1);
  13463. this._currentInstanceLocations.push(ai.index);
  13464. this._currentInstanceBuffers.push(instancesBuffer);
  13465. }
  13466. }
  13467. else {
  13468. for (var index = 0; index < 4; index++) {
  13469. var offsetLocation = offsetLocations[index];
  13470. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13471. this._gl.enableVertexAttribArray(offsetLocation);
  13472. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13473. }
  13474. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13475. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13476. this._currentInstanceLocations.push(offsetLocation);
  13477. this._currentInstanceBuffers.push(instancesBuffer);
  13478. }
  13479. }
  13480. };
  13481. /**
  13482. * Apply all cached states (depth, culling, stencil and alpha)
  13483. */
  13484. Engine.prototype.applyStates = function () {
  13485. this._depthCullingState.apply(this._gl);
  13486. this._stencilState.apply(this._gl);
  13487. this._alphaState.apply(this._gl);
  13488. };
  13489. /**
  13490. * Send a draw order
  13491. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13492. * @param indexStart defines the starting index
  13493. * @param indexCount defines the number of index to draw
  13494. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13495. */
  13496. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13497. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13498. };
  13499. /**
  13500. * Draw a list of points
  13501. * @param verticesStart defines the index of first vertex to draw
  13502. * @param verticesCount defines the count of vertices to draw
  13503. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13504. */
  13505. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13506. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13507. };
  13508. /**
  13509. * Draw a list of unindexed primitives
  13510. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13511. * @param verticesStart defines the index of first vertex to draw
  13512. * @param verticesCount defines the count of vertices to draw
  13513. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13514. */
  13515. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13516. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13517. };
  13518. /**
  13519. * Draw a list of indexed primitives
  13520. * @param fillMode defines the primitive to use
  13521. * @param indexStart defines the starting index
  13522. * @param indexCount defines the number of index to draw
  13523. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13524. */
  13525. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13526. // Apply states
  13527. this.applyStates();
  13528. this._drawCalls.addCount(1, false);
  13529. // Render
  13530. var drawMode = this._drawMode(fillMode);
  13531. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13532. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13533. if (instancesCount) {
  13534. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13535. }
  13536. else {
  13537. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13538. }
  13539. };
  13540. /**
  13541. * Draw a list of unindexed primitives
  13542. * @param fillMode defines the primitive to use
  13543. * @param verticesStart defines the index of first vertex to draw
  13544. * @param verticesCount defines the count of vertices to draw
  13545. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13546. */
  13547. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13548. // Apply states
  13549. this.applyStates();
  13550. this._drawCalls.addCount(1, false);
  13551. var drawMode = this._drawMode(fillMode);
  13552. if (instancesCount) {
  13553. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13554. }
  13555. else {
  13556. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13557. }
  13558. };
  13559. Engine.prototype._drawMode = function (fillMode) {
  13560. switch (fillMode) {
  13561. // Triangle views
  13562. case BABYLON.Material.TriangleFillMode:
  13563. return this._gl.TRIANGLES;
  13564. case BABYLON.Material.PointFillMode:
  13565. return this._gl.POINTS;
  13566. case BABYLON.Material.WireFrameFillMode:
  13567. return this._gl.LINES;
  13568. // Draw modes
  13569. case BABYLON.Material.PointListDrawMode:
  13570. return this._gl.POINTS;
  13571. case BABYLON.Material.LineListDrawMode:
  13572. return this._gl.LINES;
  13573. case BABYLON.Material.LineLoopDrawMode:
  13574. return this._gl.LINE_LOOP;
  13575. case BABYLON.Material.LineStripDrawMode:
  13576. return this._gl.LINE_STRIP;
  13577. case BABYLON.Material.TriangleStripDrawMode:
  13578. return this._gl.TRIANGLE_STRIP;
  13579. case BABYLON.Material.TriangleFanDrawMode:
  13580. return this._gl.TRIANGLE_FAN;
  13581. default:
  13582. return this._gl.TRIANGLES;
  13583. }
  13584. };
  13585. // Shaders
  13586. /** @hidden */
  13587. Engine.prototype._releaseEffect = function (effect) {
  13588. if (this._compiledEffects[effect._key]) {
  13589. delete this._compiledEffects[effect._key];
  13590. this._deleteProgram(effect.getProgram());
  13591. }
  13592. };
  13593. /** @hidden */
  13594. Engine.prototype._deleteProgram = function (program) {
  13595. if (program) {
  13596. program.__SPECTOR_rebuildProgram = null;
  13597. if (program.transformFeedback) {
  13598. this.deleteTransformFeedback(program.transformFeedback);
  13599. program.transformFeedback = null;
  13600. }
  13601. this._gl.deleteProgram(program);
  13602. }
  13603. };
  13604. /**
  13605. * Create a new effect (used to store vertex/fragment shaders)
  13606. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13607. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13608. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13609. * @param samplers defines an array of string used to represent textures
  13610. * @param defines defines the string containing the defines to use to compile the shaders
  13611. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13612. * @param onCompiled defines a function to call when the effect creation is successful
  13613. * @param onError defines a function to call when the effect creation has failed
  13614. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13615. * @returns the new Effect
  13616. */
  13617. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13618. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13619. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13620. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13621. if (this._compiledEffects[name]) {
  13622. var compiledEffect = this._compiledEffects[name];
  13623. if (onCompiled && compiledEffect.isReady()) {
  13624. onCompiled(compiledEffect);
  13625. }
  13626. return compiledEffect;
  13627. }
  13628. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13629. effect._key = name;
  13630. this._compiledEffects[name] = effect;
  13631. return effect;
  13632. };
  13633. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13634. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13635. };
  13636. ;
  13637. Engine.prototype._compileRawShader = function (source, type) {
  13638. var gl = this._gl;
  13639. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13640. gl.shaderSource(shader, source);
  13641. gl.compileShader(shader);
  13642. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13643. var log = gl.getShaderInfoLog(shader);
  13644. if (log) {
  13645. throw new Error(log);
  13646. }
  13647. }
  13648. if (!shader) {
  13649. throw new Error("Something went wrong while compile the shader.");
  13650. }
  13651. return shader;
  13652. };
  13653. ;
  13654. /**
  13655. * Directly creates a webGL program
  13656. * @param vertexCode defines the vertex shader code to use
  13657. * @param fragmentCode defines the fragment shader code to use
  13658. * @param context defines the webGL context to use (if not set, the current one will be used)
  13659. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13660. * @returns the new webGL program
  13661. */
  13662. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13663. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13664. context = context || this._gl;
  13665. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13666. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13667. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13668. };
  13669. /**
  13670. * Creates a webGL program
  13671. * @param vertexCode defines the vertex shader code to use
  13672. * @param fragmentCode defines the fragment shader code to use
  13673. * @param defines defines the string containing the defines to use to compile the shaders
  13674. * @param context defines the webGL context to use (if not set, the current one will be used)
  13675. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13676. * @returns the new webGL program
  13677. */
  13678. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13679. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13680. context = context || this._gl;
  13681. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13682. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13683. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13684. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13685. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13686. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13687. return program;
  13688. };
  13689. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13690. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13691. var shaderProgram = context.createProgram();
  13692. if (!shaderProgram) {
  13693. throw new Error("Unable to create program");
  13694. }
  13695. context.attachShader(shaderProgram, vertexShader);
  13696. context.attachShader(shaderProgram, fragmentShader);
  13697. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13698. var transformFeedback = this.createTransformFeedback();
  13699. this.bindTransformFeedback(transformFeedback);
  13700. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13701. shaderProgram.transformFeedback = transformFeedback;
  13702. }
  13703. context.linkProgram(shaderProgram);
  13704. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13705. this.bindTransformFeedback(null);
  13706. }
  13707. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13708. if (!linked) {
  13709. var error = context.getProgramInfoLog(shaderProgram);
  13710. if (error) {
  13711. throw new Error(error);
  13712. }
  13713. }
  13714. if (this.validateShaderPrograms) {
  13715. context.validateProgram(shaderProgram);
  13716. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13717. if (!validated) {
  13718. var error = context.getProgramInfoLog(shaderProgram);
  13719. if (error) {
  13720. throw new Error(error);
  13721. }
  13722. }
  13723. }
  13724. context.deleteShader(vertexShader);
  13725. context.deleteShader(fragmentShader);
  13726. return shaderProgram;
  13727. };
  13728. /**
  13729. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13730. * @param shaderProgram defines the webGL program to use
  13731. * @param uniformsNames defines the list of uniform names
  13732. * @returns an array of webGL uniform locations
  13733. */
  13734. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13735. var results = new Array();
  13736. for (var index = 0; index < uniformsNames.length; index++) {
  13737. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13738. }
  13739. return results;
  13740. };
  13741. /**
  13742. * Gets the lsit of active attributes for a given webGL program
  13743. * @param shaderProgram defines the webGL program to use
  13744. * @param attributesNames defines the list of attribute names to get
  13745. * @returns an array of indices indicating the offset of each attribute
  13746. */
  13747. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13748. var results = [];
  13749. for (var index = 0; index < attributesNames.length; index++) {
  13750. try {
  13751. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13752. }
  13753. catch (e) {
  13754. results.push(-1);
  13755. }
  13756. }
  13757. return results;
  13758. };
  13759. /**
  13760. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13761. * @param effect defines the effect to activate
  13762. */
  13763. Engine.prototype.enableEffect = function (effect) {
  13764. if (!effect) {
  13765. return;
  13766. }
  13767. // Use program
  13768. this.bindSamplers(effect);
  13769. this._currentEffect = effect;
  13770. if (effect.onBind) {
  13771. effect.onBind(effect);
  13772. }
  13773. effect.onBindObservable.notifyObservers(effect);
  13774. };
  13775. /**
  13776. * Set the value of an uniform to an array of int32
  13777. * @param uniform defines the webGL uniform location where to store the value
  13778. * @param array defines the array of int32 to store
  13779. */
  13780. Engine.prototype.setIntArray = function (uniform, array) {
  13781. if (!uniform)
  13782. return;
  13783. this._gl.uniform1iv(uniform, array);
  13784. };
  13785. /**
  13786. * Set the value of an uniform to an array of int32 (stored as vec2)
  13787. * @param uniform defines the webGL uniform location where to store the value
  13788. * @param array defines the array of int32 to store
  13789. */
  13790. Engine.prototype.setIntArray2 = function (uniform, array) {
  13791. if (!uniform || array.length % 2 !== 0)
  13792. return;
  13793. this._gl.uniform2iv(uniform, array);
  13794. };
  13795. /**
  13796. * Set the value of an uniform to an array of int32 (stored as vec3)
  13797. * @param uniform defines the webGL uniform location where to store the value
  13798. * @param array defines the array of int32 to store
  13799. */
  13800. Engine.prototype.setIntArray3 = function (uniform, array) {
  13801. if (!uniform || array.length % 3 !== 0)
  13802. return;
  13803. this._gl.uniform3iv(uniform, array);
  13804. };
  13805. /**
  13806. * Set the value of an uniform to an array of int32 (stored as vec4)
  13807. * @param uniform defines the webGL uniform location where to store the value
  13808. * @param array defines the array of int32 to store
  13809. */
  13810. Engine.prototype.setIntArray4 = function (uniform, array) {
  13811. if (!uniform || array.length % 4 !== 0)
  13812. return;
  13813. this._gl.uniform4iv(uniform, array);
  13814. };
  13815. /**
  13816. * Set the value of an uniform to an array of float32
  13817. * @param uniform defines the webGL uniform location where to store the value
  13818. * @param array defines the array of float32 to store
  13819. */
  13820. Engine.prototype.setFloatArray = function (uniform, array) {
  13821. if (!uniform)
  13822. return;
  13823. this._gl.uniform1fv(uniform, array);
  13824. };
  13825. /**
  13826. * Set the value of an uniform to an array of float32 (stored as vec2)
  13827. * @param uniform defines the webGL uniform location where to store the value
  13828. * @param array defines the array of float32 to store
  13829. */
  13830. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13831. if (!uniform || array.length % 2 !== 0)
  13832. return;
  13833. this._gl.uniform2fv(uniform, array);
  13834. };
  13835. /**
  13836. * Set the value of an uniform to an array of float32 (stored as vec3)
  13837. * @param uniform defines the webGL uniform location where to store the value
  13838. * @param array defines the array of float32 to store
  13839. */
  13840. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13841. if (!uniform || array.length % 3 !== 0)
  13842. return;
  13843. this._gl.uniform3fv(uniform, array);
  13844. };
  13845. /**
  13846. * Set the value of an uniform to an array of float32 (stored as vec4)
  13847. * @param uniform defines the webGL uniform location where to store the value
  13848. * @param array defines the array of float32 to store
  13849. */
  13850. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13851. if (!uniform || array.length % 4 !== 0)
  13852. return;
  13853. this._gl.uniform4fv(uniform, array);
  13854. };
  13855. /**
  13856. * Set the value of an uniform to an array of number
  13857. * @param uniform defines the webGL uniform location where to store the value
  13858. * @param array defines the array of number to store
  13859. */
  13860. Engine.prototype.setArray = function (uniform, array) {
  13861. if (!uniform)
  13862. return;
  13863. this._gl.uniform1fv(uniform, array);
  13864. };
  13865. /**
  13866. * Set the value of an uniform to an array of number (stored as vec2)
  13867. * @param uniform defines the webGL uniform location where to store the value
  13868. * @param array defines the array of number to store
  13869. */
  13870. Engine.prototype.setArray2 = function (uniform, array) {
  13871. if (!uniform || array.length % 2 !== 0)
  13872. return;
  13873. this._gl.uniform2fv(uniform, array);
  13874. };
  13875. /**
  13876. * Set the value of an uniform to an array of number (stored as vec3)
  13877. * @param uniform defines the webGL uniform location where to store the value
  13878. * @param array defines the array of number to store
  13879. */
  13880. Engine.prototype.setArray3 = function (uniform, array) {
  13881. if (!uniform || array.length % 3 !== 0)
  13882. return;
  13883. this._gl.uniform3fv(uniform, array);
  13884. };
  13885. /**
  13886. * Set the value of an uniform to an array of number (stored as vec4)
  13887. * @param uniform defines the webGL uniform location where to store the value
  13888. * @param array defines the array of number to store
  13889. */
  13890. Engine.prototype.setArray4 = function (uniform, array) {
  13891. if (!uniform || array.length % 4 !== 0)
  13892. return;
  13893. this._gl.uniform4fv(uniform, array);
  13894. };
  13895. /**
  13896. * Set the value of an uniform to an array of float32 (stored as matrices)
  13897. * @param uniform defines the webGL uniform location where to store the value
  13898. * @param matrices defines the array of float32 to store
  13899. */
  13900. Engine.prototype.setMatrices = function (uniform, matrices) {
  13901. if (!uniform)
  13902. return;
  13903. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13904. };
  13905. /**
  13906. * Set the value of an uniform to a matrix
  13907. * @param uniform defines the webGL uniform location where to store the value
  13908. * @param matrix defines the matrix to store
  13909. */
  13910. Engine.prototype.setMatrix = function (uniform, matrix) {
  13911. if (!uniform)
  13912. return;
  13913. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13914. };
  13915. /**
  13916. * Set the value of an uniform to a matrix (3x3)
  13917. * @param uniform defines the webGL uniform location where to store the value
  13918. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13919. */
  13920. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13921. if (!uniform)
  13922. return;
  13923. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13924. };
  13925. /**
  13926. * Set the value of an uniform to a matrix (2x2)
  13927. * @param uniform defines the webGL uniform location where to store the value
  13928. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13929. */
  13930. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13931. if (!uniform)
  13932. return;
  13933. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13934. };
  13935. /**
  13936. * Set the value of an uniform to a number (int)
  13937. * @param uniform defines the webGL uniform location where to store the value
  13938. * @param value defines the int number to store
  13939. */
  13940. Engine.prototype.setInt = function (uniform, value) {
  13941. if (!uniform)
  13942. return;
  13943. this._gl.uniform1i(uniform, value);
  13944. };
  13945. /**
  13946. * Set the value of an uniform to a number (float)
  13947. * @param uniform defines the webGL uniform location where to store the value
  13948. * @param value defines the float number to store
  13949. */
  13950. Engine.prototype.setFloat = function (uniform, value) {
  13951. if (!uniform)
  13952. return;
  13953. this._gl.uniform1f(uniform, value);
  13954. };
  13955. /**
  13956. * Set the value of an uniform to a vec2
  13957. * @param uniform defines the webGL uniform location where to store the value
  13958. * @param x defines the 1st component of the value
  13959. * @param y defines the 2nd component of the value
  13960. */
  13961. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13962. if (!uniform)
  13963. return;
  13964. this._gl.uniform2f(uniform, x, y);
  13965. };
  13966. /**
  13967. * Set the value of an uniform to a vec3
  13968. * @param uniform defines the webGL uniform location where to store the value
  13969. * @param x defines the 1st component of the value
  13970. * @param y defines the 2nd component of the value
  13971. * @param z defines the 3rd component of the value
  13972. */
  13973. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13974. if (!uniform)
  13975. return;
  13976. this._gl.uniform3f(uniform, x, y, z);
  13977. };
  13978. /**
  13979. * Set the value of an uniform to a boolean
  13980. * @param uniform defines the webGL uniform location where to store the value
  13981. * @param bool defines the boolean to store
  13982. */
  13983. Engine.prototype.setBool = function (uniform, bool) {
  13984. if (!uniform)
  13985. return;
  13986. this._gl.uniform1i(uniform, bool);
  13987. };
  13988. /**
  13989. * Set the value of an uniform to a vec4
  13990. * @param uniform defines the webGL uniform location where to store the value
  13991. * @param x defines the 1st component of the value
  13992. * @param y defines the 2nd component of the value
  13993. * @param z defines the 3rd component of the value
  13994. * @param w defines the 4th component of the value
  13995. */
  13996. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13997. if (!uniform)
  13998. return;
  13999. this._gl.uniform4f(uniform, x, y, z, w);
  14000. };
  14001. /**
  14002. * Set the value of an uniform to a Color3
  14003. * @param uniform defines the webGL uniform location where to store the value
  14004. * @param color3 defines the color to store
  14005. */
  14006. Engine.prototype.setColor3 = function (uniform, color3) {
  14007. if (!uniform)
  14008. return;
  14009. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14010. };
  14011. /**
  14012. * Set the value of an uniform to a Color3 and an alpha value
  14013. * @param uniform defines the webGL uniform location where to store the value
  14014. * @param color3 defines the color to store
  14015. * @param alpha defines the alpha component to store
  14016. */
  14017. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14018. if (!uniform)
  14019. return;
  14020. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14021. };
  14022. /**
  14023. * Sets a Color4 on a uniform variable
  14024. * @param uniform defines the uniform location
  14025. * @param color4 defines the value to be set
  14026. */
  14027. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14028. if (!uniform)
  14029. return;
  14030. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14031. };
  14032. // States
  14033. /**
  14034. * Set various states to the webGL context
  14035. * @param culling defines backface culling state
  14036. * @param zOffset defines the value to apply to zOffset (0 by default)
  14037. * @param force defines if states must be applied even if cache is up to date
  14038. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14039. */
  14040. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14041. if (zOffset === void 0) { zOffset = 0; }
  14042. if (reverseSide === void 0) { reverseSide = false; }
  14043. // Culling
  14044. if (this._depthCullingState.cull !== culling || force) {
  14045. this._depthCullingState.cull = culling;
  14046. }
  14047. // Cull face
  14048. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14049. if (this._depthCullingState.cullFace !== cullFace || force) {
  14050. this._depthCullingState.cullFace = cullFace;
  14051. }
  14052. // Z offset
  14053. this.setZOffset(zOffset);
  14054. // Front face
  14055. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14056. if (this._depthCullingState.frontFace !== frontFace || force) {
  14057. this._depthCullingState.frontFace = frontFace;
  14058. }
  14059. };
  14060. /**
  14061. * Set the z offset to apply to current rendering
  14062. * @param value defines the offset to apply
  14063. */
  14064. Engine.prototype.setZOffset = function (value) {
  14065. this._depthCullingState.zOffset = value;
  14066. };
  14067. /**
  14068. * Gets the current value of the zOffset
  14069. * @returns the current zOffset state
  14070. */
  14071. Engine.prototype.getZOffset = function () {
  14072. return this._depthCullingState.zOffset;
  14073. };
  14074. /**
  14075. * Enable or disable depth buffering
  14076. * @param enable defines the state to set
  14077. */
  14078. Engine.prototype.setDepthBuffer = function (enable) {
  14079. this._depthCullingState.depthTest = enable;
  14080. };
  14081. /**
  14082. * Gets a boolean indicating if depth writing is enabled
  14083. * @returns the current depth writing state
  14084. */
  14085. Engine.prototype.getDepthWrite = function () {
  14086. return this._depthCullingState.depthMask;
  14087. };
  14088. /**
  14089. * Enable or disable depth writing
  14090. * @param enable defines the state to set
  14091. */
  14092. Engine.prototype.setDepthWrite = function (enable) {
  14093. this._depthCullingState.depthMask = enable;
  14094. };
  14095. /**
  14096. * Enable or disable color writing
  14097. * @param enable defines the state to set
  14098. */
  14099. Engine.prototype.setColorWrite = function (enable) {
  14100. this._gl.colorMask(enable, enable, enable, enable);
  14101. this._colorWrite = enable;
  14102. };
  14103. /**
  14104. * Gets a boolean indicating if color writing is enabled
  14105. * @returns the current color writing state
  14106. */
  14107. Engine.prototype.getColorWrite = function () {
  14108. return this._colorWrite;
  14109. };
  14110. /**
  14111. * Sets alpha constants used by some alpha blending modes
  14112. * @param r defines the red component
  14113. * @param g defines the green component
  14114. * @param b defines the blue component
  14115. * @param a defines the alpha component
  14116. */
  14117. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14118. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14119. };
  14120. /**
  14121. * Sets the current alpha mode
  14122. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14123. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14124. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14125. */
  14126. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14127. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14128. if (this._alphaMode === mode) {
  14129. return;
  14130. }
  14131. switch (mode) {
  14132. case Engine.ALPHA_DISABLE:
  14133. this._alphaState.alphaBlend = false;
  14134. break;
  14135. case Engine.ALPHA_PREMULTIPLIED:
  14136. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14137. this._alphaState.alphaBlend = true;
  14138. break;
  14139. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14140. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14141. this._alphaState.alphaBlend = true;
  14142. break;
  14143. case Engine.ALPHA_COMBINE:
  14144. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14145. this._alphaState.alphaBlend = true;
  14146. break;
  14147. case Engine.ALPHA_ONEONE:
  14148. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14149. this._alphaState.alphaBlend = true;
  14150. break;
  14151. case Engine.ALPHA_ADD:
  14152. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14153. this._alphaState.alphaBlend = true;
  14154. break;
  14155. case Engine.ALPHA_SUBTRACT:
  14156. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14157. this._alphaState.alphaBlend = true;
  14158. break;
  14159. case Engine.ALPHA_MULTIPLY:
  14160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14161. this._alphaState.alphaBlend = true;
  14162. break;
  14163. case Engine.ALPHA_MAXIMIZED:
  14164. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14165. this._alphaState.alphaBlend = true;
  14166. break;
  14167. case Engine.ALPHA_INTERPOLATE:
  14168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14169. this._alphaState.alphaBlend = true;
  14170. break;
  14171. case Engine.ALPHA_SCREENMODE:
  14172. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14173. this._alphaState.alphaBlend = true;
  14174. break;
  14175. }
  14176. if (!noDepthWriteChange) {
  14177. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14178. }
  14179. this._alphaMode = mode;
  14180. };
  14181. /**
  14182. * Gets the current alpha mode
  14183. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14184. * @returns the current alpha mode
  14185. */
  14186. Engine.prototype.getAlphaMode = function () {
  14187. return this._alphaMode;
  14188. };
  14189. // Textures
  14190. /**
  14191. * Clears the list of texture accessible through engine.
  14192. * This can help preventing texture load conflict due to name collision.
  14193. */
  14194. Engine.prototype.clearInternalTexturesCache = function () {
  14195. this._internalTexturesCache = [];
  14196. };
  14197. /**
  14198. * Force the entire cache to be cleared
  14199. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14200. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14201. */
  14202. Engine.prototype.wipeCaches = function (bruteForce) {
  14203. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14204. return;
  14205. }
  14206. this._currentEffect = null;
  14207. this._unpackFlipYCached = null;
  14208. this._viewportCached.x = 0;
  14209. this._viewportCached.y = 0;
  14210. this._viewportCached.z = 0;
  14211. this._viewportCached.w = 0;
  14212. if (bruteForce) {
  14213. this.resetTextureCache();
  14214. this._currentProgram = null;
  14215. this._stencilState.reset();
  14216. this._depthCullingState.reset();
  14217. this.setDepthFunctionToLessOrEqual();
  14218. this._alphaState.reset();
  14219. }
  14220. this._resetVertexBufferBinding();
  14221. this._cachedIndexBuffer = null;
  14222. this._cachedEffectForVertexBuffers = null;
  14223. this._unbindVertexArrayObject();
  14224. this.bindIndexBuffer(null);
  14225. };
  14226. /**
  14227. * Set the compressed texture format to use, based on the formats you have, and the formats
  14228. * supported by the hardware / browser.
  14229. *
  14230. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14231. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14232. * to API arguments needed to compressed textures. This puts the burden on the container
  14233. * generator to house the arcane code for determining these for current & future formats.
  14234. *
  14235. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14236. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14237. *
  14238. * Note: The result of this call is not taken into account when a texture is base64.
  14239. *
  14240. * @param formatsAvailable defines the list of those format families you have created
  14241. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14242. *
  14243. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14244. * @returns The extension selected.
  14245. */
  14246. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14247. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14248. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14249. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14250. return this._textureFormatInUse = this._texturesSupported[i];
  14251. }
  14252. }
  14253. }
  14254. // actively set format to nothing, to allow this to be called more than once
  14255. // and possibly fail the 2nd time
  14256. this._textureFormatInUse = null;
  14257. return null;
  14258. };
  14259. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14260. var gl = this._gl;
  14261. var magFilter = gl.NEAREST;
  14262. var minFilter = gl.NEAREST;
  14263. switch (samplingMode) {
  14264. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14265. magFilter = gl.LINEAR;
  14266. if (generateMipMaps) {
  14267. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14268. }
  14269. else {
  14270. minFilter = gl.LINEAR;
  14271. }
  14272. break;
  14273. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14274. magFilter = gl.LINEAR;
  14275. if (generateMipMaps) {
  14276. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14277. }
  14278. else {
  14279. minFilter = gl.LINEAR;
  14280. }
  14281. break;
  14282. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14283. magFilter = gl.NEAREST;
  14284. if (generateMipMaps) {
  14285. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14286. }
  14287. else {
  14288. minFilter = gl.NEAREST;
  14289. }
  14290. break;
  14291. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14292. magFilter = gl.NEAREST;
  14293. if (generateMipMaps) {
  14294. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14295. }
  14296. else {
  14297. minFilter = gl.NEAREST;
  14298. }
  14299. break;
  14300. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14301. magFilter = gl.NEAREST;
  14302. if (generateMipMaps) {
  14303. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14304. }
  14305. else {
  14306. minFilter = gl.LINEAR;
  14307. }
  14308. break;
  14309. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14310. magFilter = gl.NEAREST;
  14311. if (generateMipMaps) {
  14312. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14313. }
  14314. else {
  14315. minFilter = gl.LINEAR;
  14316. }
  14317. break;
  14318. case Engine.TEXTURE_NEAREST_LINEAR:
  14319. magFilter = gl.NEAREST;
  14320. minFilter = gl.LINEAR;
  14321. break;
  14322. case Engine.TEXTURE_NEAREST_NEAREST:
  14323. magFilter = gl.NEAREST;
  14324. minFilter = gl.NEAREST;
  14325. break;
  14326. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14327. magFilter = gl.LINEAR;
  14328. if (generateMipMaps) {
  14329. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14330. }
  14331. else {
  14332. minFilter = gl.NEAREST;
  14333. }
  14334. break;
  14335. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14336. magFilter = gl.LINEAR;
  14337. if (generateMipMaps) {
  14338. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14339. }
  14340. else {
  14341. minFilter = gl.NEAREST;
  14342. }
  14343. break;
  14344. case Engine.TEXTURE_LINEAR_LINEAR:
  14345. magFilter = gl.LINEAR;
  14346. minFilter = gl.LINEAR;
  14347. break;
  14348. case Engine.TEXTURE_LINEAR_NEAREST:
  14349. magFilter = gl.LINEAR;
  14350. minFilter = gl.NEAREST;
  14351. break;
  14352. }
  14353. return {
  14354. min: minFilter,
  14355. mag: magFilter
  14356. };
  14357. };
  14358. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14359. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14360. var img;
  14361. var onload = function () {
  14362. loadedImages[index] = img;
  14363. loadedImages._internalCount++;
  14364. if (scene) {
  14365. scene._removePendingData(img);
  14366. }
  14367. if (loadedImages._internalCount === 6) {
  14368. onfinish(loadedImages);
  14369. }
  14370. };
  14371. var onerror = function (message, exception) {
  14372. if (scene) {
  14373. scene._removePendingData(img);
  14374. }
  14375. if (onErrorCallBack) {
  14376. onErrorCallBack(message, exception);
  14377. }
  14378. };
  14379. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14380. if (scene) {
  14381. scene._addPendingData(img);
  14382. }
  14383. };
  14384. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14385. if (onError === void 0) { onError = null; }
  14386. var loadedImages = [];
  14387. loadedImages._internalCount = 0;
  14388. for (var index = 0; index < 6; index++) {
  14389. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14390. }
  14391. };
  14392. ;
  14393. /** @hidden */
  14394. Engine.prototype._createTexture = function () {
  14395. var texture = this._gl.createTexture();
  14396. if (!texture) {
  14397. throw new Error("Unable to create texture");
  14398. }
  14399. return texture;
  14400. };
  14401. /**
  14402. * Usually called from BABYLON.Texture.ts.
  14403. * Passed information to create a WebGLTexture
  14404. * @param urlArg defines a value which contains one of the following:
  14405. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14406. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14407. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14408. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14409. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14410. * @param scene needed for loading to the correct scene
  14411. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14412. * @param onLoad optional callback to be called upon successful completion
  14413. * @param onError optional callback to be called upon failure
  14414. * @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
  14415. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14416. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14417. * @param forcedExtension defines the extension to use to pick the right loader
  14418. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14419. */
  14420. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14421. var _this = this;
  14422. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14423. if (onLoad === void 0) { onLoad = null; }
  14424. if (onError === void 0) { onError = null; }
  14425. if (buffer === void 0) { buffer = null; }
  14426. if (fallback === void 0) { fallback = null; }
  14427. if (format === void 0) { format = null; }
  14428. if (forcedExtension === void 0) { forcedExtension = null; }
  14429. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14430. var fromData = url.substr(0, 5) === "data:";
  14431. var fromBlob = url.substr(0, 5) === "blob:";
  14432. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14433. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14434. // establish the file extension, if possible
  14435. var lastDot = url.lastIndexOf('.');
  14436. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14437. var loader = null;
  14438. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14439. var availableLoader = _a[_i];
  14440. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14441. loader = availableLoader;
  14442. break;
  14443. }
  14444. }
  14445. if (loader) {
  14446. url = loader.transformUrl(url, this._textureFormatInUse);
  14447. }
  14448. if (scene) {
  14449. scene._addPendingData(texture);
  14450. }
  14451. texture.url = url;
  14452. texture.generateMipMaps = !noMipmap;
  14453. texture.samplingMode = samplingMode;
  14454. texture.invertY = invertY;
  14455. if (!this._doNotHandleContextLost) {
  14456. // Keep a link to the buffer only if we plan to handle context lost
  14457. texture._buffer = buffer;
  14458. }
  14459. var onLoadObserver = null;
  14460. if (onLoad && !fallback) {
  14461. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14462. }
  14463. if (!fallback)
  14464. this._internalTexturesCache.push(texture);
  14465. var onInternalError = function (message, exception) {
  14466. if (scene) {
  14467. scene._removePendingData(texture);
  14468. }
  14469. var customFallback = false;
  14470. if (loader) {
  14471. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14472. if (fallbackUrl) {
  14473. // Add Back
  14474. customFallback = true;
  14475. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14476. }
  14477. }
  14478. if (!customFallback) {
  14479. if (onLoadObserver) {
  14480. texture.onLoadedObservable.remove(onLoadObserver);
  14481. }
  14482. if (BABYLON.Tools.UseFallbackTexture) {
  14483. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14484. }
  14485. }
  14486. if (onError) {
  14487. onError(message || "Unknown error", exception);
  14488. }
  14489. };
  14490. // processing for non-image formats
  14491. if (loader) {
  14492. var callback = function (data) {
  14493. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14494. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14495. done();
  14496. return false;
  14497. }, samplingMode);
  14498. });
  14499. };
  14500. if (!buffer) {
  14501. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14502. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14503. });
  14504. }
  14505. else {
  14506. callback(buffer);
  14507. }
  14508. }
  14509. else {
  14510. var onload = function (img) {
  14511. if (fromBlob && !_this._doNotHandleContextLost) {
  14512. // We need to store the image if we need to rebuild the texture
  14513. // in case of a webgl context lost
  14514. texture._buffer = img;
  14515. }
  14516. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14517. var gl = _this._gl;
  14518. var isPot = (img.width === potWidth && img.height === potHeight);
  14519. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14520. if (isPot) {
  14521. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14522. return false;
  14523. }
  14524. var maxTextureSize = _this._caps.maxTextureSize;
  14525. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14526. _this._prepareWorkingCanvas();
  14527. if (!_this._workingCanvas || !_this._workingContext) {
  14528. return false;
  14529. }
  14530. _this._workingCanvas.width = potWidth;
  14531. _this._workingCanvas.height = potHeight;
  14532. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14533. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14534. texture.width = potWidth;
  14535. texture.height = potHeight;
  14536. return false;
  14537. }
  14538. else {
  14539. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14540. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14541. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14542. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14543. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14544. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14545. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14547. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14548. _this._releaseTexture(source_1);
  14549. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14550. continuationCallback();
  14551. });
  14552. }
  14553. return true;
  14554. }, samplingMode);
  14555. };
  14556. if (!fromData || isBase64) {
  14557. if (buffer instanceof HTMLImageElement) {
  14558. onload(buffer);
  14559. }
  14560. else {
  14561. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14562. }
  14563. }
  14564. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14565. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14566. }
  14567. else {
  14568. onload(buffer);
  14569. }
  14570. }
  14571. return texture;
  14572. };
  14573. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14574. var _this = this;
  14575. var rtt = this.createRenderTargetTexture({
  14576. width: destination.width,
  14577. height: destination.height,
  14578. }, {
  14579. generateMipMaps: false,
  14580. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14581. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14582. generateDepthBuffer: false,
  14583. generateStencilBuffer: false
  14584. });
  14585. if (!this._rescalePostProcess) {
  14586. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14587. }
  14588. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14589. _this._rescalePostProcess.onApply = function (effect) {
  14590. effect._bindTexture("textureSampler", source);
  14591. };
  14592. var hostingScene = scene;
  14593. if (!hostingScene) {
  14594. hostingScene = _this.scenes[_this.scenes.length - 1];
  14595. }
  14596. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14597. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14598. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14599. _this.unBindFramebuffer(rtt);
  14600. _this._releaseTexture(rtt);
  14601. if (onComplete) {
  14602. onComplete();
  14603. }
  14604. });
  14605. };
  14606. /**
  14607. * Update a raw texture
  14608. * @param texture defines the texture to update
  14609. * @param data defines the data to store in the texture
  14610. * @param format defines the format of the data
  14611. * @param invertY defines if data must be stored with Y axis inverted
  14612. * @param compression defines the compression used (null by default)
  14613. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14614. */
  14615. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14616. if (compression === void 0) { compression = null; }
  14617. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14618. if (!texture) {
  14619. return;
  14620. }
  14621. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14622. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14623. // babylon's internalFormat but gl's texImage2D format
  14624. var internalFormat = this._getInternalFormat(format);
  14625. var textureType = this._getWebGLTextureType(type);
  14626. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14627. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14628. if (!this._doNotHandleContextLost) {
  14629. texture._bufferView = data;
  14630. texture.format = format;
  14631. texture.type = type;
  14632. texture.invertY = invertY;
  14633. texture._compression = compression;
  14634. }
  14635. if (texture.width % 4 !== 0) {
  14636. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14637. }
  14638. if (compression && data) {
  14639. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14640. }
  14641. else {
  14642. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14643. }
  14644. if (texture.generateMipMaps) {
  14645. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14646. }
  14647. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14648. // this.resetTextureCache();
  14649. texture.isReady = true;
  14650. };
  14651. /**
  14652. * Creates a raw texture
  14653. * @param data defines the data to store in the texture
  14654. * @param width defines the width of the texture
  14655. * @param height defines the height of the texture
  14656. * @param format defines the format of the data
  14657. * @param generateMipMaps defines if the engine should generate the mip levels
  14658. * @param invertY defines if data must be stored with Y axis inverted
  14659. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14660. * @param compression defines the compression used (null by default)
  14661. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14662. * @returns the raw texture inside an InternalTexture
  14663. */
  14664. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14665. if (compression === void 0) { compression = null; }
  14666. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14667. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14668. texture.baseWidth = width;
  14669. texture.baseHeight = height;
  14670. texture.width = width;
  14671. texture.height = height;
  14672. texture.format = format;
  14673. texture.generateMipMaps = generateMipMaps;
  14674. texture.samplingMode = samplingMode;
  14675. texture.invertY = invertY;
  14676. texture._compression = compression;
  14677. texture.type = type;
  14678. if (!this._doNotHandleContextLost) {
  14679. texture._bufferView = data;
  14680. }
  14681. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14682. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14683. // Filters
  14684. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14685. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14686. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14687. if (generateMipMaps) {
  14688. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14689. }
  14690. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14691. this._internalTexturesCache.push(texture);
  14692. return texture;
  14693. };
  14694. /** @hidden */
  14695. Engine.prototype._unpackFlipY = function (value) {
  14696. if (this._unpackFlipYCached !== value) {
  14697. this._unpackFlipYCached = value;
  14698. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14699. }
  14700. };
  14701. /** @hidden */
  14702. Engine.prototype._getUnpackAlignement = function () {
  14703. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14704. };
  14705. /**
  14706. * Creates a dynamic texture
  14707. * @param width defines the width of the texture
  14708. * @param height defines the height of the texture
  14709. * @param generateMipMaps defines if the engine should generate the mip levels
  14710. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14711. * @returns the dynamic texture inside an InternalTexture
  14712. */
  14713. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14714. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14715. texture.baseWidth = width;
  14716. texture.baseHeight = height;
  14717. if (generateMipMaps) {
  14718. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14719. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14720. }
  14721. // this.resetTextureCache();
  14722. texture.width = width;
  14723. texture.height = height;
  14724. texture.isReady = false;
  14725. texture.generateMipMaps = generateMipMaps;
  14726. texture.samplingMode = samplingMode;
  14727. this.updateTextureSamplingMode(samplingMode, texture);
  14728. this._internalTexturesCache.push(texture);
  14729. return texture;
  14730. };
  14731. /**
  14732. * Update the sampling mode of a given texture
  14733. * @param samplingMode defines the required sampling mode
  14734. * @param texture defines the texture to update
  14735. */
  14736. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14737. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14738. if (texture.isCube) {
  14739. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14740. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14741. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14742. }
  14743. else if (texture.is3D) {
  14744. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14745. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14746. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14747. }
  14748. else {
  14749. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14750. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14751. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14752. }
  14753. texture.samplingMode = samplingMode;
  14754. };
  14755. /**
  14756. * Update the content of a dynamic texture
  14757. * @param texture defines the texture to update
  14758. * @param canvas defines the canvas containing the source
  14759. * @param invertY defines if data must be stored with Y axis inverted
  14760. * @param premulAlpha defines if alpha is stored as premultiplied
  14761. * @param format defines the format of the data
  14762. */
  14763. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14764. if (premulAlpha === void 0) { premulAlpha = false; }
  14765. if (!texture) {
  14766. return;
  14767. }
  14768. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14769. this._unpackFlipY(invertY);
  14770. if (premulAlpha) {
  14771. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14772. }
  14773. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14774. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14775. if (texture.generateMipMaps) {
  14776. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14777. }
  14778. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14779. if (premulAlpha) {
  14780. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14781. }
  14782. texture.isReady = true;
  14783. };
  14784. /**
  14785. * Update a video texture
  14786. * @param texture defines the texture to update
  14787. * @param video defines the video element to use
  14788. * @param invertY defines if data must be stored with Y axis inverted
  14789. */
  14790. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14791. if (!texture || texture._isDisabled) {
  14792. return;
  14793. }
  14794. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14795. this._unpackFlipY(!invertY); // Video are upside down by default
  14796. try {
  14797. // Testing video texture support
  14798. if (this._videoTextureSupported === undefined) {
  14799. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14800. if (this._gl.getError() !== 0) {
  14801. this._videoTextureSupported = false;
  14802. }
  14803. else {
  14804. this._videoTextureSupported = true;
  14805. }
  14806. }
  14807. // Copy video through the current working canvas if video texture is not supported
  14808. if (!this._videoTextureSupported) {
  14809. if (!texture._workingCanvas) {
  14810. texture._workingCanvas = document.createElement("canvas");
  14811. var context = texture._workingCanvas.getContext("2d");
  14812. if (!context) {
  14813. throw new Error("Unable to get 2d context");
  14814. }
  14815. texture._workingContext = context;
  14816. texture._workingCanvas.width = texture.width;
  14817. texture._workingCanvas.height = texture.height;
  14818. }
  14819. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14820. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14821. }
  14822. else {
  14823. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14824. }
  14825. if (texture.generateMipMaps) {
  14826. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14827. }
  14828. if (!wasPreviouslyBound) {
  14829. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14830. }
  14831. // this.resetTextureCache();
  14832. texture.isReady = true;
  14833. }
  14834. catch (ex) {
  14835. // Something unexpected
  14836. // Let's disable the texture
  14837. texture._isDisabled = true;
  14838. }
  14839. };
  14840. /**
  14841. * Updates a depth texture Comparison Mode and Function.
  14842. * If the comparison Function is equal to 0, the mode will be set to none.
  14843. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14844. * @param texture The texture to set the comparison function for
  14845. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14846. */
  14847. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14848. if (this.webGLVersion === 1) {
  14849. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14850. return;
  14851. }
  14852. var gl = this._gl;
  14853. if (texture.isCube) {
  14854. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14855. if (comparisonFunction === 0) {
  14856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14858. }
  14859. else {
  14860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14862. }
  14863. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14864. }
  14865. else {
  14866. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14867. if (comparisonFunction === 0) {
  14868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14870. }
  14871. else {
  14872. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14874. }
  14875. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14876. }
  14877. texture._comparisonFunction = comparisonFunction;
  14878. };
  14879. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14880. var width = size.width || size;
  14881. var height = size.height || size;
  14882. internalTexture.baseWidth = width;
  14883. internalTexture.baseHeight = height;
  14884. internalTexture.width = width;
  14885. internalTexture.height = height;
  14886. internalTexture.isReady = true;
  14887. internalTexture.samples = 1;
  14888. internalTexture.generateMipMaps = false;
  14889. internalTexture._generateDepthBuffer = true;
  14890. internalTexture._generateStencilBuffer = generateStencil;
  14891. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14892. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14893. internalTexture._comparisonFunction = comparisonFunction;
  14894. var gl = this._gl;
  14895. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14896. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14897. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14898. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14899. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14900. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14901. if (comparisonFunction === 0) {
  14902. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14903. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14904. }
  14905. else {
  14906. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14907. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14908. }
  14909. };
  14910. /**
  14911. * Creates a depth stencil texture.
  14912. * This is only available in WebGL 2 or with the depth texture extension available.
  14913. * @param size The size of face edge in the texture.
  14914. * @param options The options defining the texture.
  14915. * @returns The texture
  14916. */
  14917. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14918. if (options.isCube) {
  14919. var width = size.width || size;
  14920. return this._createDepthStencilCubeTexture(width, options);
  14921. }
  14922. else {
  14923. return this._createDepthStencilTexture(size, options);
  14924. }
  14925. };
  14926. /**
  14927. * Creates a depth stencil texture.
  14928. * This is only available in WebGL 2 or with the depth texture extension available.
  14929. * @param size The size of face edge in the texture.
  14930. * @param options The options defining the texture.
  14931. * @returns The texture
  14932. */
  14933. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14934. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14935. if (!this._caps.depthTextureExtension) {
  14936. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14937. return internalTexture;
  14938. }
  14939. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14940. var gl = this._gl;
  14941. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14942. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14943. if (this.webGLVersion > 1) {
  14944. if (internalOptions.generateStencil) {
  14945. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14946. }
  14947. else {
  14948. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14949. }
  14950. }
  14951. else {
  14952. if (internalOptions.generateStencil) {
  14953. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14954. }
  14955. else {
  14956. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14957. }
  14958. }
  14959. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14960. return internalTexture;
  14961. };
  14962. /**
  14963. * Creates a depth stencil cube texture.
  14964. * This is only available in WebGL 2.
  14965. * @param size The size of face edge in the cube texture.
  14966. * @param options The options defining the cube texture.
  14967. * @returns The cube texture
  14968. */
  14969. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14970. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14971. internalTexture.isCube = true;
  14972. if (this.webGLVersion === 1) {
  14973. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14974. return internalTexture;
  14975. }
  14976. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14977. var gl = this._gl;
  14978. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14979. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14980. // Create the depth/stencil buffer
  14981. for (var face = 0; face < 6; face++) {
  14982. if (internalOptions.generateStencil) {
  14983. 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);
  14984. }
  14985. else {
  14986. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14987. }
  14988. }
  14989. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14990. return internalTexture;
  14991. };
  14992. /**
  14993. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14994. * @param renderTarget The render target to set the frame buffer for
  14995. */
  14996. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14997. // Create the framebuffer
  14998. var internalTexture = renderTarget.getInternalTexture();
  14999. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15000. return;
  15001. }
  15002. var gl = this._gl;
  15003. var depthStencilTexture = renderTarget.depthStencilTexture;
  15004. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15005. if (depthStencilTexture.isCube) {
  15006. if (depthStencilTexture._generateStencilBuffer) {
  15007. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15008. }
  15009. else {
  15010. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15011. }
  15012. }
  15013. else {
  15014. if (depthStencilTexture._generateStencilBuffer) {
  15015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15016. }
  15017. else {
  15018. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15019. }
  15020. }
  15021. this.bindUnboundFramebuffer(null);
  15022. };
  15023. /**
  15024. * Creates a new render target texture
  15025. * @param size defines the size of the texture
  15026. * @param options defines the options used to create the texture
  15027. * @returns a new render target texture stored in an InternalTexture
  15028. */
  15029. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15030. var fullOptions = new RenderTargetCreationOptions();
  15031. if (options !== undefined && typeof options === "object") {
  15032. fullOptions.generateMipMaps = options.generateMipMaps;
  15033. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15034. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15035. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15036. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15037. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15038. }
  15039. else {
  15040. fullOptions.generateMipMaps = options;
  15041. fullOptions.generateDepthBuffer = true;
  15042. fullOptions.generateStencilBuffer = false;
  15043. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15044. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15045. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15046. }
  15047. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15048. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15049. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15050. }
  15051. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15052. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15053. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15054. }
  15055. var gl = this._gl;
  15056. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15057. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15058. var width = size.width || size;
  15059. var height = size.height || size;
  15060. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15061. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15062. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15063. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15064. }
  15065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15067. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15068. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15069. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15070. // Create the framebuffer
  15071. var currentFrameBuffer = this._currentFramebuffer;
  15072. var framebuffer = gl.createFramebuffer();
  15073. this.bindUnboundFramebuffer(framebuffer);
  15074. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15075. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15076. if (fullOptions.generateMipMaps) {
  15077. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15078. }
  15079. // Unbind
  15080. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15081. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15082. this.bindUnboundFramebuffer(currentFrameBuffer);
  15083. texture._framebuffer = framebuffer;
  15084. texture.baseWidth = width;
  15085. texture.baseHeight = height;
  15086. texture.width = width;
  15087. texture.height = height;
  15088. texture.isReady = true;
  15089. texture.samples = 1;
  15090. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15091. texture.samplingMode = fullOptions.samplingMode;
  15092. texture.type = fullOptions.type;
  15093. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15094. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15095. // this.resetTextureCache();
  15096. this._internalTexturesCache.push(texture);
  15097. return texture;
  15098. };
  15099. /**
  15100. * Create a multi render target texture
  15101. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15102. * @param size defines the size of the texture
  15103. * @param options defines the creation options
  15104. * @returns the cube texture as an InternalTexture
  15105. */
  15106. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15107. var generateMipMaps = false;
  15108. var generateDepthBuffer = true;
  15109. var generateStencilBuffer = false;
  15110. var generateDepthTexture = false;
  15111. var textureCount = 1;
  15112. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15113. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15114. var types = new Array();
  15115. var samplingModes = new Array();
  15116. if (options !== undefined) {
  15117. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15118. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15119. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15120. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15121. textureCount = options.textureCount || 1;
  15122. if (options.types) {
  15123. types = options.types;
  15124. }
  15125. if (options.samplingModes) {
  15126. samplingModes = options.samplingModes;
  15127. }
  15128. }
  15129. var gl = this._gl;
  15130. // Create the framebuffer
  15131. var framebuffer = gl.createFramebuffer();
  15132. this.bindUnboundFramebuffer(framebuffer);
  15133. var width = size.width || size;
  15134. var height = size.height || size;
  15135. var textures = [];
  15136. var attachments = [];
  15137. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15138. for (var i = 0; i < textureCount; i++) {
  15139. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15140. var type = types[i] || defaultType;
  15141. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15142. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15143. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15144. }
  15145. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15146. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15147. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15148. }
  15149. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15150. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15151. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15152. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15153. }
  15154. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15155. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15156. textures.push(texture);
  15157. attachments.push(attachment);
  15158. gl.activeTexture(gl["TEXTURE" + i]);
  15159. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15164. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15165. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15166. if (generateMipMaps) {
  15167. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15168. }
  15169. // Unbind
  15170. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15171. texture._framebuffer = framebuffer;
  15172. texture._depthStencilBuffer = depthStencilBuffer;
  15173. texture.baseWidth = width;
  15174. texture.baseHeight = height;
  15175. texture.width = width;
  15176. texture.height = height;
  15177. texture.isReady = true;
  15178. texture.samples = 1;
  15179. texture.generateMipMaps = generateMipMaps;
  15180. texture.samplingMode = samplingMode;
  15181. texture.type = type;
  15182. texture._generateDepthBuffer = generateDepthBuffer;
  15183. texture._generateStencilBuffer = generateStencilBuffer;
  15184. texture._attachments = attachments;
  15185. this._internalTexturesCache.push(texture);
  15186. }
  15187. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15188. // Depth texture
  15189. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15190. gl.activeTexture(gl.TEXTURE0);
  15191. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15196. 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);
  15197. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15198. depthTexture._framebuffer = framebuffer;
  15199. depthTexture.baseWidth = width;
  15200. depthTexture.baseHeight = height;
  15201. depthTexture.width = width;
  15202. depthTexture.height = height;
  15203. depthTexture.isReady = true;
  15204. depthTexture.samples = 1;
  15205. depthTexture.generateMipMaps = generateMipMaps;
  15206. depthTexture.samplingMode = gl.NEAREST;
  15207. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15208. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15209. textures.push(depthTexture);
  15210. this._internalTexturesCache.push(depthTexture);
  15211. }
  15212. gl.drawBuffers(attachments);
  15213. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15214. this.bindUnboundFramebuffer(null);
  15215. this.resetTextureCache();
  15216. return textures;
  15217. };
  15218. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15219. if (samples === void 0) { samples = 1; }
  15220. var depthStencilBuffer = null;
  15221. var gl = this._gl;
  15222. // Create the depth/stencil buffer
  15223. if (generateStencilBuffer) {
  15224. depthStencilBuffer = gl.createRenderbuffer();
  15225. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15226. if (samples > 1) {
  15227. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15228. }
  15229. else {
  15230. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15231. }
  15232. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15233. }
  15234. else if (generateDepthBuffer) {
  15235. depthStencilBuffer = gl.createRenderbuffer();
  15236. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15237. if (samples > 1) {
  15238. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15239. }
  15240. else {
  15241. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15242. }
  15243. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15244. }
  15245. return depthStencilBuffer;
  15246. };
  15247. /**
  15248. * Updates the sample count of a render target texture
  15249. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15250. * @param texture defines the texture to update
  15251. * @param samples defines the sample count to set
  15252. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15253. */
  15254. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15255. if (this.webGLVersion < 2 || !texture) {
  15256. return 1;
  15257. }
  15258. if (texture.samples === samples) {
  15259. return samples;
  15260. }
  15261. var gl = this._gl;
  15262. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15263. // Dispose previous render buffers
  15264. if (texture._depthStencilBuffer) {
  15265. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15266. texture._depthStencilBuffer = null;
  15267. }
  15268. if (texture._MSAAFramebuffer) {
  15269. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15270. texture._MSAAFramebuffer = null;
  15271. }
  15272. if (texture._MSAARenderBuffer) {
  15273. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15274. texture._MSAARenderBuffer = null;
  15275. }
  15276. if (samples > 1) {
  15277. var framebuffer = gl.createFramebuffer();
  15278. if (!framebuffer) {
  15279. throw new Error("Unable to create multi sampled framebuffer");
  15280. }
  15281. texture._MSAAFramebuffer = framebuffer;
  15282. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15283. var colorRenderbuffer = gl.createRenderbuffer();
  15284. if (!colorRenderbuffer) {
  15285. throw new Error("Unable to create multi sampled framebuffer");
  15286. }
  15287. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15288. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15289. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15290. texture._MSAARenderBuffer = colorRenderbuffer;
  15291. }
  15292. else {
  15293. this.bindUnboundFramebuffer(texture._framebuffer);
  15294. }
  15295. texture.samples = samples;
  15296. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15297. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15298. this.bindUnboundFramebuffer(null);
  15299. return samples;
  15300. };
  15301. /**
  15302. * Update the sample count for a given multiple render target texture
  15303. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15304. * @param textures defines the textures to update
  15305. * @param samples defines the sample count to set
  15306. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15307. */
  15308. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15309. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15310. return 1;
  15311. }
  15312. if (textures[0].samples === samples) {
  15313. return samples;
  15314. }
  15315. var gl = this._gl;
  15316. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15317. // Dispose previous render buffers
  15318. if (textures[0]._depthStencilBuffer) {
  15319. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15320. textures[0]._depthStencilBuffer = null;
  15321. }
  15322. if (textures[0]._MSAAFramebuffer) {
  15323. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15324. textures[0]._MSAAFramebuffer = null;
  15325. }
  15326. for (var i = 0; i < textures.length; i++) {
  15327. if (textures[i]._MSAARenderBuffer) {
  15328. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15329. textures[i]._MSAARenderBuffer = null;
  15330. }
  15331. }
  15332. if (samples > 1) {
  15333. var framebuffer = gl.createFramebuffer();
  15334. if (!framebuffer) {
  15335. throw new Error("Unable to create multi sampled framebuffer");
  15336. }
  15337. this.bindUnboundFramebuffer(framebuffer);
  15338. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15339. var attachments = [];
  15340. for (var i = 0; i < textures.length; i++) {
  15341. var texture = textures[i];
  15342. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15343. var colorRenderbuffer = gl.createRenderbuffer();
  15344. if (!colorRenderbuffer) {
  15345. throw new Error("Unable to create multi sampled framebuffer");
  15346. }
  15347. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15348. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15349. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15350. texture._MSAAFramebuffer = framebuffer;
  15351. texture._MSAARenderBuffer = colorRenderbuffer;
  15352. texture.samples = samples;
  15353. texture._depthStencilBuffer = depthStencilBuffer;
  15354. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15355. attachments.push(attachment);
  15356. }
  15357. gl.drawBuffers(attachments);
  15358. }
  15359. else {
  15360. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15361. }
  15362. this.bindUnboundFramebuffer(null);
  15363. return samples;
  15364. };
  15365. /** @hidden */
  15366. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15367. if (faceIndex === void 0) { faceIndex = 0; }
  15368. if (lod === void 0) { lod = 0; }
  15369. var gl = this._gl;
  15370. var target = gl.TEXTURE_2D;
  15371. if (texture.isCube) {
  15372. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15373. }
  15374. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15375. };
  15376. /** @hidden */
  15377. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15378. if (faceIndex === void 0) { faceIndex = 0; }
  15379. if (lod === void 0) { lod = 0; }
  15380. var gl = this._gl;
  15381. var textureType = this._getWebGLTextureType(texture.type);
  15382. var format = this._getInternalFormat(texture.format);
  15383. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15384. this._unpackFlipY(texture.invertY);
  15385. var target = gl.TEXTURE_2D;
  15386. if (texture.isCube) {
  15387. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15388. }
  15389. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15390. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15391. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15392. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15393. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15394. };
  15395. /** @hidden */
  15396. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15397. if (faceIndex === void 0) { faceIndex = 0; }
  15398. if (lod === void 0) { lod = 0; }
  15399. var gl = this._gl;
  15400. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15401. this._bindTextureDirectly(bindTarget, texture, true);
  15402. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15403. this._bindTextureDirectly(bindTarget, null, true);
  15404. };
  15405. /** @hidden */
  15406. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15407. if (faceIndex === void 0) { faceIndex = 0; }
  15408. if (lod === void 0) { lod = 0; }
  15409. var gl = this._gl;
  15410. var textureType = this._getWebGLTextureType(texture.type);
  15411. var format = this._getInternalFormat(texture.format);
  15412. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15413. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15414. this._bindTextureDirectly(bindTarget, texture, true);
  15415. this._unpackFlipY(texture.invertY);
  15416. var target = gl.TEXTURE_2D;
  15417. if (texture.isCube) {
  15418. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15419. }
  15420. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15421. this._bindTextureDirectly(bindTarget, null, true);
  15422. };
  15423. /**
  15424. * Creates a new render target cube texture
  15425. * @param size defines the size of the texture
  15426. * @param options defines the options used to create the texture
  15427. * @returns a new render target cube texture stored in an InternalTexture
  15428. */
  15429. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15430. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15431. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15432. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15433. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15434. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15435. }
  15436. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15437. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15438. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15439. }
  15440. var gl = this._gl;
  15441. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15442. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15443. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15444. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15445. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15446. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15447. }
  15448. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15449. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15450. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15451. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15452. for (var face = 0; face < 6; face++) {
  15453. 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);
  15454. }
  15455. // Create the framebuffer
  15456. var framebuffer = gl.createFramebuffer();
  15457. this.bindUnboundFramebuffer(framebuffer);
  15458. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15459. // MipMaps
  15460. if (fullOptions.generateMipMaps) {
  15461. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15462. }
  15463. // Unbind
  15464. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15465. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15466. this.bindUnboundFramebuffer(null);
  15467. texture._framebuffer = framebuffer;
  15468. texture.width = size;
  15469. texture.height = size;
  15470. texture.isReady = true;
  15471. texture.isCube = true;
  15472. texture.samples = 1;
  15473. texture.generateMipMaps = fullOptions.generateMipMaps;
  15474. texture.samplingMode = fullOptions.samplingMode;
  15475. texture.type = fullOptions.type;
  15476. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15477. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15478. this._internalTexturesCache.push(texture);
  15479. return texture;
  15480. };
  15481. /**
  15482. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15483. * @param rootUrl defines the url where the file to load is located
  15484. * @param scene defines the current scene
  15485. * @param lodScale defines scale to apply to the mip map selection
  15486. * @param lodOffset defines offset to apply to the mip map selection
  15487. * @param onLoad defines an optional callback raised when the texture is loaded
  15488. * @param onError defines an optional callback raised if there is an issue to load the texture
  15489. * @param format defines the format of the data
  15490. * @param forcedExtension defines the extension to use to pick the right loader
  15491. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15492. * @returns the cube texture as an InternalTexture
  15493. */
  15494. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15495. var _this = this;
  15496. if (onLoad === void 0) { onLoad = null; }
  15497. if (onError === void 0) { onError = null; }
  15498. if (forcedExtension === void 0) { forcedExtension = null; }
  15499. if (createPolynomials === void 0) { createPolynomials = true; }
  15500. var callback = function (loadData) {
  15501. if (!loadData) {
  15502. if (onLoad) {
  15503. onLoad(null);
  15504. }
  15505. return;
  15506. }
  15507. var texture = loadData.texture;
  15508. if (!createPolynomials) {
  15509. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15510. }
  15511. else if (loadData.info.sphericalPolynomial) {
  15512. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15513. }
  15514. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15515. if (_this._caps.textureLOD) {
  15516. // Do not add extra process if texture lod is supported.
  15517. if (onLoad) {
  15518. onLoad(texture);
  15519. }
  15520. return;
  15521. }
  15522. var mipSlices = 3;
  15523. var gl = _this._gl;
  15524. var width = loadData.width;
  15525. if (!width) {
  15526. return;
  15527. }
  15528. var textures = [];
  15529. for (var i = 0; i < mipSlices; i++) {
  15530. //compute LOD from even spacing in smoothness (matching shader calculation)
  15531. var smoothness = i / (mipSlices - 1);
  15532. var roughness = 1 - smoothness;
  15533. var minLODIndex = lodOffset; // roughness = 0
  15534. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15535. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15536. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15537. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15538. glTextureFromLod.type = texture.type;
  15539. glTextureFromLod.format = texture.format;
  15540. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15541. glTextureFromLod.height = glTextureFromLod.width;
  15542. glTextureFromLod.isCube = true;
  15543. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15544. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15548. if (loadData.isDDS) {
  15549. var info = loadData.info;
  15550. var data = loadData.data;
  15551. _this._unpackFlipY(info.isCompressed);
  15552. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15553. }
  15554. else {
  15555. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15556. }
  15557. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15558. // Wrap in a base texture for easy binding.
  15559. var lodTexture = new BABYLON.BaseTexture(scene);
  15560. lodTexture.isCube = true;
  15561. lodTexture._texture = glTextureFromLod;
  15562. glTextureFromLod.isReady = true;
  15563. textures.push(lodTexture);
  15564. }
  15565. texture._lodTextureHigh = textures[2];
  15566. texture._lodTextureMid = textures[1];
  15567. texture._lodTextureLow = textures[0];
  15568. if (onLoad) {
  15569. onLoad(texture);
  15570. }
  15571. };
  15572. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15573. };
  15574. /**
  15575. * Creates a cube texture
  15576. * @param rootUrl defines the url where the files to load is located
  15577. * @param scene defines the current scene
  15578. * @param files defines the list of files to load (1 per face)
  15579. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15580. * @param onLoad defines an optional callback raised when the texture is loaded
  15581. * @param onError defines an optional callback raised if there is an issue to load the texture
  15582. * @param format defines the format of the data
  15583. * @param forcedExtension defines the extension to use to pick the right loader
  15584. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15585. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15586. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15587. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15588. * @returns the cube texture as an InternalTexture
  15589. */
  15590. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15591. var _this = this;
  15592. if (onLoad === void 0) { onLoad = null; }
  15593. if (onError === void 0) { onError = null; }
  15594. if (forcedExtension === void 0) { forcedExtension = null; }
  15595. if (createPolynomials === void 0) { createPolynomials = false; }
  15596. if (lodScale === void 0) { lodScale = 0; }
  15597. if (lodOffset === void 0) { lodOffset = 0; }
  15598. if (fallback === void 0) { fallback = null; }
  15599. var gl = this._gl;
  15600. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15601. texture.isCube = true;
  15602. texture.url = rootUrl;
  15603. texture.generateMipMaps = !noMipmap;
  15604. texture._lodGenerationScale = lodScale;
  15605. texture._lodGenerationOffset = lodOffset;
  15606. if (!this._doNotHandleContextLost) {
  15607. texture._extension = forcedExtension;
  15608. texture._files = files;
  15609. }
  15610. var lastDot = rootUrl.lastIndexOf('.');
  15611. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15612. var loader = null;
  15613. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15614. var availableLoader = _a[_i];
  15615. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15616. loader = availableLoader;
  15617. break;
  15618. }
  15619. }
  15620. var onInternalError = function (request, exception) {
  15621. if (loader) {
  15622. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15623. if (fallbackUrl) {
  15624. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15625. }
  15626. }
  15627. if (onError && request) {
  15628. onError(request.status + " " + request.statusText, exception);
  15629. }
  15630. };
  15631. if (loader) {
  15632. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15633. var onloaddata = function (data) {
  15634. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15635. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15636. };
  15637. if (files && files.length === 6) {
  15638. if (loader.supportCascades) {
  15639. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15640. }
  15641. else if (onError) {
  15642. onError("Textures type does not support cascades.");
  15643. }
  15644. }
  15645. else {
  15646. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15647. }
  15648. }
  15649. else {
  15650. if (!files) {
  15651. throw new Error("Cannot load cubemap because files were not defined");
  15652. }
  15653. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15654. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15655. var height = width;
  15656. _this._prepareWorkingCanvas();
  15657. if (!_this._workingCanvas || !_this._workingContext) {
  15658. return;
  15659. }
  15660. _this._workingCanvas.width = width;
  15661. _this._workingCanvas.height = height;
  15662. var faces = [
  15663. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15664. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15665. ];
  15666. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15667. _this._unpackFlipY(false);
  15668. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15669. for (var index = 0; index < faces.length; index++) {
  15670. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15671. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15672. }
  15673. if (!noMipmap) {
  15674. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15675. }
  15676. _this._setCubeMapTextureParams(!noMipmap);
  15677. texture.width = width;
  15678. texture.height = height;
  15679. texture.isReady = true;
  15680. if (format) {
  15681. texture.format = format;
  15682. }
  15683. texture.onLoadedObservable.notifyObservers(texture);
  15684. texture.onLoadedObservable.clear();
  15685. if (onLoad) {
  15686. onLoad();
  15687. }
  15688. }, files, onError);
  15689. }
  15690. this._internalTexturesCache.push(texture);
  15691. return texture;
  15692. };
  15693. /**
  15694. * @hidden
  15695. */
  15696. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15697. var gl = this._gl;
  15698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : 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. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15703. // this.resetTextureCache();
  15704. };
  15705. /**
  15706. * Update a raw cube texture
  15707. * @param texture defines the texture to udpdate
  15708. * @param data defines the data to store
  15709. * @param format defines the data format
  15710. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15711. * @param invertY defines if data must be stored with Y axis inverted
  15712. * @param compression defines the compression used (null by default)
  15713. * @param level defines which level of the texture to update
  15714. */
  15715. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15716. if (compression === void 0) { compression = null; }
  15717. if (level === void 0) { level = 0; }
  15718. texture._bufferViewArray = data;
  15719. texture.format = format;
  15720. texture.type = type;
  15721. texture.invertY = invertY;
  15722. texture._compression = compression;
  15723. var gl = this._gl;
  15724. var textureType = this._getWebGLTextureType(type);
  15725. var internalFormat = this._getInternalFormat(format);
  15726. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15727. var needConversion = false;
  15728. if (internalFormat === gl.RGB) {
  15729. internalFormat = gl.RGBA;
  15730. needConversion = true;
  15731. }
  15732. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15733. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15734. if (texture.width % 4 !== 0) {
  15735. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15736. }
  15737. // Data are known to be in +X +Y +Z -X -Y -Z
  15738. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15739. var faceData = data[faceIndex];
  15740. if (compression) {
  15741. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15742. }
  15743. else {
  15744. if (needConversion) {
  15745. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15746. }
  15747. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15748. }
  15749. }
  15750. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15751. if (isPot && texture.generateMipMaps && level === 0) {
  15752. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15753. }
  15754. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15755. // this.resetTextureCache();
  15756. texture.isReady = true;
  15757. };
  15758. /**
  15759. * Creates a new raw cube texture
  15760. * @param data defines the array of data to use to create each face
  15761. * @param size defines the size of the textures
  15762. * @param format defines the format of the data
  15763. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15764. * @param generateMipMaps defines if the engine should generate the mip levels
  15765. * @param invertY defines if data must be stored with Y axis inverted
  15766. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15767. * @param compression defines the compression used (null by default)
  15768. * @returns the cube texture as an InternalTexture
  15769. */
  15770. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15771. if (compression === void 0) { compression = null; }
  15772. var gl = this._gl;
  15773. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15774. texture.isCube = true;
  15775. texture.format = format;
  15776. texture.type = type;
  15777. if (!this._doNotHandleContextLost) {
  15778. texture._bufferViewArray = data;
  15779. }
  15780. var textureType = this._getWebGLTextureType(type);
  15781. var internalFormat = this._getInternalFormat(format);
  15782. if (internalFormat === gl.RGB) {
  15783. internalFormat = gl.RGBA;
  15784. }
  15785. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15786. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15787. generateMipMaps = false;
  15788. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15789. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15790. }
  15791. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15792. generateMipMaps = false;
  15793. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15794. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15795. }
  15796. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15797. generateMipMaps = false;
  15798. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15799. }
  15800. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15801. generateMipMaps = false;
  15802. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15803. }
  15804. var width = size;
  15805. var height = width;
  15806. texture.width = width;
  15807. texture.height = height;
  15808. // Double check on POT to generate Mips.
  15809. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15810. if (!isPot) {
  15811. generateMipMaps = false;
  15812. }
  15813. // Upload data if needed. The texture won't be ready until then.
  15814. if (data) {
  15815. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15816. }
  15817. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15818. // Filters
  15819. if (data && generateMipMaps) {
  15820. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15821. }
  15822. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15827. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15828. texture.generateMipMaps = generateMipMaps;
  15829. return texture;
  15830. };
  15831. /**
  15832. * Creates a new raw cube texture from a specified url
  15833. * @param url defines the url where the data is located
  15834. * @param scene defines the current scene
  15835. * @param size defines the size of the textures
  15836. * @param format defines the format of the data
  15837. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15838. * @param noMipmap defines if the engine should avoid generating the mip levels
  15839. * @param callback defines a callback used to extract texture data from loaded data
  15840. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15841. * @param onLoad defines a callback called when texture is loaded
  15842. * @param onError defines a callback called if there is an error
  15843. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15844. * @param invertY defines if data must be stored with Y axis inverted
  15845. * @returns the cube texture as an InternalTexture
  15846. */
  15847. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15848. var _this = this;
  15849. if (onLoad === void 0) { onLoad = null; }
  15850. if (onError === void 0) { onError = null; }
  15851. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15852. if (invertY === void 0) { invertY = false; }
  15853. var gl = this._gl;
  15854. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15855. scene._addPendingData(texture);
  15856. texture.url = url;
  15857. this._internalTexturesCache.push(texture);
  15858. var onerror = function (request, exception) {
  15859. scene._removePendingData(texture);
  15860. if (onError && request) {
  15861. onError(request.status + " " + request.statusText, exception);
  15862. }
  15863. };
  15864. var internalCallback = function (data) {
  15865. var width = texture.width;
  15866. var faceDataArrays = callback(data);
  15867. if (!faceDataArrays) {
  15868. return;
  15869. }
  15870. if (mipmapGenerator) {
  15871. var textureType = _this._getWebGLTextureType(type);
  15872. var internalFormat = _this._getInternalFormat(format);
  15873. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15874. var needConversion = false;
  15875. if (internalFormat === gl.RGB) {
  15876. internalFormat = gl.RGBA;
  15877. needConversion = true;
  15878. }
  15879. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15880. _this._unpackFlipY(false);
  15881. var mipData = mipmapGenerator(faceDataArrays);
  15882. for (var level = 0; level < mipData.length; level++) {
  15883. var mipSize = width >> level;
  15884. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15885. var mipFaceData = mipData[level][faceIndex];
  15886. if (needConversion) {
  15887. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15888. }
  15889. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15890. }
  15891. }
  15892. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15893. }
  15894. else {
  15895. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15896. }
  15897. texture.isReady = true;
  15898. // this.resetTextureCache();
  15899. scene._removePendingData(texture);
  15900. if (onLoad) {
  15901. onLoad();
  15902. }
  15903. };
  15904. this._loadFile(url, function (data) {
  15905. internalCallback(data);
  15906. }, undefined, scene.database, true, onerror);
  15907. return texture;
  15908. };
  15909. ;
  15910. /**
  15911. * Update a raw 3D texture
  15912. * @param texture defines the texture to update
  15913. * @param data defines the data to store
  15914. * @param format defines the data format
  15915. * @param invertY defines if data must be stored with Y axis inverted
  15916. * @param compression defines the used compression (can be null)
  15917. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15918. */
  15919. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15920. if (compression === void 0) { compression = null; }
  15921. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15922. var internalType = this._getWebGLTextureType(textureType);
  15923. var internalFormat = this._getInternalFormat(format);
  15924. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15925. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15926. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15927. if (!this._doNotHandleContextLost) {
  15928. texture._bufferView = data;
  15929. texture.format = format;
  15930. texture.invertY = invertY;
  15931. texture._compression = compression;
  15932. }
  15933. if (texture.width % 4 !== 0) {
  15934. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15935. }
  15936. if (compression && data) {
  15937. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15938. }
  15939. else {
  15940. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15941. }
  15942. if (texture.generateMipMaps) {
  15943. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15944. }
  15945. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15946. // this.resetTextureCache();
  15947. texture.isReady = true;
  15948. };
  15949. /**
  15950. * Creates a new raw 3D texture
  15951. * @param data defines the data used to create the texture
  15952. * @param width defines the width of the texture
  15953. * @param height defines the height of the texture
  15954. * @param depth defines the depth of the texture
  15955. * @param format defines the format of the texture
  15956. * @param generateMipMaps defines if the engine must generate mip levels
  15957. * @param invertY defines if data must be stored with Y axis inverted
  15958. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15959. * @param compression defines the compressed used (can be null)
  15960. * @param textureType defines the compressed used (can be null)
  15961. * @returns a new raw 3D texture (stored in an InternalTexture)
  15962. */
  15963. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15964. if (compression === void 0) { compression = null; }
  15965. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15966. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15967. texture.baseWidth = width;
  15968. texture.baseHeight = height;
  15969. texture.baseDepth = depth;
  15970. texture.width = width;
  15971. texture.height = height;
  15972. texture.depth = depth;
  15973. texture.format = format;
  15974. texture.type = textureType;
  15975. texture.generateMipMaps = generateMipMaps;
  15976. texture.samplingMode = samplingMode;
  15977. texture.is3D = true;
  15978. if (!this._doNotHandleContextLost) {
  15979. texture._bufferView = data;
  15980. }
  15981. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15982. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15983. // Filters
  15984. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15985. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15986. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15987. if (generateMipMaps) {
  15988. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15989. }
  15990. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15991. this._internalTexturesCache.push(texture);
  15992. return texture;
  15993. };
  15994. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15995. var gl = this._gl;
  15996. if (!gl) {
  15997. return;
  15998. }
  15999. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16002. if (!noMipmap && !isCompressed) {
  16003. gl.generateMipmap(gl.TEXTURE_2D);
  16004. }
  16005. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16006. // this.resetTextureCache();
  16007. if (scene) {
  16008. scene._removePendingData(texture);
  16009. }
  16010. texture.onLoadedObservable.notifyObservers(texture);
  16011. texture.onLoadedObservable.clear();
  16012. };
  16013. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16014. var _this = this;
  16015. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16016. var maxTextureSize = this.getCaps().maxTextureSize;
  16017. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16018. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16019. var gl = this._gl;
  16020. if (!gl) {
  16021. return;
  16022. }
  16023. if (!texture._webGLTexture) {
  16024. // this.resetTextureCache();
  16025. if (scene) {
  16026. scene._removePendingData(texture);
  16027. }
  16028. return;
  16029. }
  16030. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16031. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16032. texture.baseWidth = width;
  16033. texture.baseHeight = height;
  16034. texture.width = potWidth;
  16035. texture.height = potHeight;
  16036. texture.isReady = true;
  16037. if (processFunction(potWidth, potHeight, function () {
  16038. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16039. })) {
  16040. // Returning as texture needs extra async steps
  16041. return;
  16042. }
  16043. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16044. };
  16045. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16046. // Create new RGBA data container.
  16047. var rgbaData;
  16048. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16049. rgbaData = new Float32Array(width * height * 4);
  16050. }
  16051. else {
  16052. rgbaData = new Uint32Array(width * height * 4);
  16053. }
  16054. // Convert each pixel.
  16055. for (var x = 0; x < width; x++) {
  16056. for (var y = 0; y < height; y++) {
  16057. var index = (y * width + x) * 3;
  16058. var newIndex = (y * width + x) * 4;
  16059. // Map Old Value to new value.
  16060. rgbaData[newIndex + 0] = rgbData[index + 0];
  16061. rgbaData[newIndex + 1] = rgbData[index + 1];
  16062. rgbaData[newIndex + 2] = rgbData[index + 2];
  16063. // Add fully opaque alpha channel.
  16064. rgbaData[newIndex + 3] = 1;
  16065. }
  16066. }
  16067. return rgbaData;
  16068. };
  16069. /** @hidden */
  16070. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16071. var gl = this._gl;
  16072. if (texture._framebuffer) {
  16073. gl.deleteFramebuffer(texture._framebuffer);
  16074. texture._framebuffer = null;
  16075. }
  16076. if (texture._depthStencilBuffer) {
  16077. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16078. texture._depthStencilBuffer = null;
  16079. }
  16080. if (texture._MSAAFramebuffer) {
  16081. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16082. texture._MSAAFramebuffer = null;
  16083. }
  16084. if (texture._MSAARenderBuffer) {
  16085. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16086. texture._MSAARenderBuffer = null;
  16087. }
  16088. };
  16089. /** @hidden */
  16090. Engine.prototype._releaseTexture = function (texture) {
  16091. var gl = this._gl;
  16092. this._releaseFramebufferObjects(texture);
  16093. gl.deleteTexture(texture._webGLTexture);
  16094. // Unbind channels
  16095. this.unbindAllTextures();
  16096. var index = this._internalTexturesCache.indexOf(texture);
  16097. if (index !== -1) {
  16098. this._internalTexturesCache.splice(index, 1);
  16099. }
  16100. // Integrated fixed lod samplers.
  16101. if (texture._lodTextureHigh) {
  16102. texture._lodTextureHigh.dispose();
  16103. }
  16104. if (texture._lodTextureMid) {
  16105. texture._lodTextureMid.dispose();
  16106. }
  16107. if (texture._lodTextureLow) {
  16108. texture._lodTextureLow.dispose();
  16109. }
  16110. // Set output texture of post process to null if the texture has been released/disposed
  16111. this.scenes.forEach(function (scene) {
  16112. scene.postProcesses.forEach(function (postProcess) {
  16113. if (postProcess._outputTexture == texture) {
  16114. postProcess._outputTexture = null;
  16115. }
  16116. });
  16117. scene.cameras.forEach(function (camera) {
  16118. camera._postProcesses.forEach(function (postProcess) {
  16119. if (postProcess) {
  16120. if (postProcess._outputTexture == texture) {
  16121. postProcess._outputTexture = null;
  16122. }
  16123. }
  16124. });
  16125. });
  16126. });
  16127. };
  16128. Engine.prototype.setProgram = function (program) {
  16129. if (this._currentProgram !== program) {
  16130. this._gl.useProgram(program);
  16131. this._currentProgram = program;
  16132. }
  16133. };
  16134. /**
  16135. * Binds an effect to the webGL context
  16136. * @param effect defines the effect to bind
  16137. */
  16138. Engine.prototype.bindSamplers = function (effect) {
  16139. this.setProgram(effect.getProgram());
  16140. var samplers = effect.getSamplers();
  16141. for (var index = 0; index < samplers.length; index++) {
  16142. var uniform = effect.getUniform(samplers[index]);
  16143. if (uniform) {
  16144. this._boundUniforms[index] = uniform;
  16145. }
  16146. }
  16147. this._currentEffect = null;
  16148. };
  16149. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16150. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16151. return;
  16152. }
  16153. // Remove
  16154. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16155. // Bind last to it
  16156. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16157. // Bind to dummy
  16158. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16159. };
  16160. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16161. if (!internalTexture) {
  16162. return -1;
  16163. }
  16164. internalTexture._initialSlot = channel;
  16165. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16166. if (channel !== internalTexture._designatedSlot) {
  16167. this._textureCollisions.addCount(1, false);
  16168. }
  16169. }
  16170. else {
  16171. if (channel !== internalTexture._designatedSlot) {
  16172. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16173. return internalTexture._designatedSlot;
  16174. }
  16175. else {
  16176. // No slot for this texture, let's pick a new one (if we find a free slot)
  16177. if (this._nextFreeTextureSlots.length) {
  16178. return this._nextFreeTextureSlots[0];
  16179. }
  16180. // We need to recycle the oldest bound texture, sorry.
  16181. this._textureCollisions.addCount(1, false);
  16182. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16183. }
  16184. }
  16185. }
  16186. return channel;
  16187. };
  16188. Engine.prototype._linkTrackers = function (previous, next) {
  16189. previous.next = next;
  16190. next.previous = previous;
  16191. };
  16192. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16193. var currentSlot = internalTexture._designatedSlot;
  16194. if (currentSlot === -1) {
  16195. return -1;
  16196. }
  16197. internalTexture._designatedSlot = -1;
  16198. if (this.disableTextureBindingOptimization) {
  16199. return -1;
  16200. }
  16201. // Remove from bound list
  16202. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16203. // Free the slot
  16204. this._boundTexturesCache[currentSlot] = null;
  16205. this._nextFreeTextureSlots.push(currentSlot);
  16206. return currentSlot;
  16207. };
  16208. Engine.prototype._activateCurrentTexture = function () {
  16209. if (this._currentTextureChannel !== this._activeChannel) {
  16210. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16211. this._currentTextureChannel = this._activeChannel;
  16212. }
  16213. };
  16214. /** @hidden */
  16215. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16216. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16217. if (force === void 0) { force = false; }
  16218. var wasPreviouslyBound = false;
  16219. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16220. this._activeChannel = texture._designatedSlot;
  16221. }
  16222. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16223. var isTextureForRendering = texture && texture._initialSlot > -1;
  16224. if (currentTextureBound !== texture || force) {
  16225. if (currentTextureBound) {
  16226. this._removeDesignatedSlot(currentTextureBound);
  16227. }
  16228. this._activateCurrentTexture();
  16229. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16230. this._boundTexturesCache[this._activeChannel] = texture;
  16231. if (texture) {
  16232. if (!this.disableTextureBindingOptimization) {
  16233. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16234. if (slotIndex > -1) {
  16235. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16236. }
  16237. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16238. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16239. }
  16240. texture._designatedSlot = this._activeChannel;
  16241. }
  16242. }
  16243. else if (forTextureDataUpdate) {
  16244. wasPreviouslyBound = true;
  16245. this._activateCurrentTexture();
  16246. }
  16247. if (isTextureForRendering && !forTextureDataUpdate) {
  16248. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16249. }
  16250. return wasPreviouslyBound;
  16251. };
  16252. /** @hidden */
  16253. Engine.prototype._bindTexture = function (channel, texture) {
  16254. if (channel < 0) {
  16255. return;
  16256. }
  16257. if (texture) {
  16258. channel = this._getCorrectTextureChannel(channel, texture);
  16259. }
  16260. this._activeChannel = channel;
  16261. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16262. };
  16263. /**
  16264. * Sets a texture to the webGL context from a postprocess
  16265. * @param channel defines the channel to use
  16266. * @param postProcess defines the source postprocess
  16267. */
  16268. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16269. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16270. };
  16271. /**
  16272. * Binds the output of the passed in post process to the texture channel specified
  16273. * @param channel The channel the texture should be bound to
  16274. * @param postProcess The post process which's output should be bound
  16275. */
  16276. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16277. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16278. };
  16279. /**
  16280. * Unbind all textures from the webGL context
  16281. */
  16282. Engine.prototype.unbindAllTextures = function () {
  16283. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16284. this._activeChannel = channel;
  16285. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16286. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16287. if (this.webGLVersion > 1) {
  16288. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16289. }
  16290. }
  16291. };
  16292. /**
  16293. * Sets a texture to the according uniform.
  16294. * @param channel The texture channel
  16295. * @param uniform The uniform to set
  16296. * @param texture The texture to apply
  16297. */
  16298. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16299. if (channel < 0) {
  16300. return;
  16301. }
  16302. if (uniform) {
  16303. this._boundUniforms[channel] = uniform;
  16304. }
  16305. this._setTexture(channel, texture);
  16306. };
  16307. /**
  16308. * Sets a depth stencil texture from a render target to the according uniform.
  16309. * @param channel The texture channel
  16310. * @param uniform The uniform to set
  16311. * @param texture The render target texture containing the depth stencil texture to apply
  16312. */
  16313. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16314. if (channel < 0) {
  16315. return;
  16316. }
  16317. if (uniform) {
  16318. this._boundUniforms[channel] = uniform;
  16319. }
  16320. if (!texture || !texture.depthStencilTexture) {
  16321. this._setTexture(channel, null);
  16322. }
  16323. else {
  16324. this._setTexture(channel, texture, false, true);
  16325. }
  16326. };
  16327. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16328. var uniform = this._boundUniforms[sourceSlot];
  16329. if (uniform._currentState === destination) {
  16330. return;
  16331. }
  16332. this._gl.uniform1i(uniform, destination);
  16333. uniform._currentState = destination;
  16334. };
  16335. Engine.prototype._getTextureWrapMode = function (mode) {
  16336. switch (mode) {
  16337. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16338. return this._gl.REPEAT;
  16339. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16340. return this._gl.CLAMP_TO_EDGE;
  16341. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16342. return this._gl.MIRRORED_REPEAT;
  16343. }
  16344. return this._gl.REPEAT;
  16345. };
  16346. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16347. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16348. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16349. // Not ready?
  16350. if (!texture) {
  16351. if (this._boundTexturesCache[channel] != null) {
  16352. this._activeChannel = channel;
  16353. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16354. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16355. if (this.webGLVersion > 1) {
  16356. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16357. }
  16358. }
  16359. return false;
  16360. }
  16361. // Video
  16362. if (texture.video) {
  16363. this._activeChannel = channel;
  16364. texture.update();
  16365. }
  16366. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16367. texture.delayLoad();
  16368. return false;
  16369. }
  16370. var internalTexture;
  16371. if (depthStencilTexture) {
  16372. internalTexture = texture.depthStencilTexture;
  16373. }
  16374. else if (texture.isReady()) {
  16375. internalTexture = texture.getInternalTexture();
  16376. }
  16377. else if (texture.isCube) {
  16378. internalTexture = this.emptyCubeTexture;
  16379. }
  16380. else if (texture.is3D) {
  16381. internalTexture = this.emptyTexture3D;
  16382. }
  16383. else {
  16384. internalTexture = this.emptyTexture;
  16385. }
  16386. if (!isPartOfTextureArray) {
  16387. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16388. }
  16389. var needToBind = true;
  16390. if (this._boundTexturesCache[channel] === internalTexture) {
  16391. this._moveBoundTextureOnTop(internalTexture);
  16392. if (!isPartOfTextureArray) {
  16393. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16394. }
  16395. needToBind = false;
  16396. }
  16397. this._activeChannel = channel;
  16398. if (internalTexture && internalTexture.is3D) {
  16399. if (needToBind) {
  16400. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16401. }
  16402. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16403. internalTexture._cachedWrapU = texture.wrapU;
  16404. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16405. }
  16406. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16407. internalTexture._cachedWrapV = texture.wrapV;
  16408. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16409. }
  16410. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16411. internalTexture._cachedWrapR = texture.wrapR;
  16412. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16413. }
  16414. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16415. }
  16416. else if (internalTexture && internalTexture.isCube) {
  16417. if (needToBind) {
  16418. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16419. }
  16420. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16421. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16422. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16423. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16424. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16425. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16426. }
  16427. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16428. }
  16429. else {
  16430. if (needToBind) {
  16431. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16432. }
  16433. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16434. internalTexture._cachedWrapU = texture.wrapU;
  16435. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16436. }
  16437. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16438. internalTexture._cachedWrapV = texture.wrapV;
  16439. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16440. }
  16441. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16442. }
  16443. return true;
  16444. };
  16445. /**
  16446. * Sets an array of texture to the webGL context
  16447. * @param channel defines the channel where the texture array must be set
  16448. * @param uniform defines the associated uniform location
  16449. * @param textures defines the array of textures to bind
  16450. */
  16451. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16452. if (channel < 0 || !uniform) {
  16453. return;
  16454. }
  16455. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16456. this._textureUnits = new Int32Array(textures.length);
  16457. }
  16458. for (var i = 0; i < textures.length; i++) {
  16459. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16460. }
  16461. this._gl.uniform1iv(uniform, this._textureUnits);
  16462. for (var index = 0; index < textures.length; index++) {
  16463. this._setTexture(this._textureUnits[index], textures[index], true);
  16464. }
  16465. };
  16466. /** @hidden */
  16467. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16468. var internalTexture = texture.getInternalTexture();
  16469. if (!internalTexture) {
  16470. return;
  16471. }
  16472. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16473. var value = texture.anisotropicFilteringLevel;
  16474. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16475. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16476. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16477. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16478. }
  16479. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16480. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16481. internalTexture._cachedAnisotropicFilteringLevel = value;
  16482. }
  16483. };
  16484. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16485. this._bindTextureDirectly(target, texture, true, true);
  16486. this._gl.texParameterf(target, parameter, value);
  16487. };
  16488. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16489. if (texture) {
  16490. this._bindTextureDirectly(target, texture, true, true);
  16491. }
  16492. this._gl.texParameteri(target, parameter, value);
  16493. };
  16494. /**
  16495. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16496. * @param x defines the x coordinate of the rectangle where pixels must be read
  16497. * @param y defines the y coordinate of the rectangle where pixels must be read
  16498. * @param width defines the width of the rectangle where pixels must be read
  16499. * @param height defines the height of the rectangle where pixels must be read
  16500. * @returns a Uint8Array containing RGBA colors
  16501. */
  16502. Engine.prototype.readPixels = function (x, y, width, height) {
  16503. var data = new Uint8Array(height * width * 4);
  16504. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16505. return data;
  16506. };
  16507. /**
  16508. * Add an externaly attached data from its key.
  16509. * This method call will fail and return false, if such key already exists.
  16510. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16511. * @param key the unique key that identifies the data
  16512. * @param data the data object to associate to the key for this Engine instance
  16513. * @return true if no such key were already present and the data was added successfully, false otherwise
  16514. */
  16515. Engine.prototype.addExternalData = function (key, data) {
  16516. if (!this._externalData) {
  16517. this._externalData = new BABYLON.StringDictionary();
  16518. }
  16519. return this._externalData.add(key, data);
  16520. };
  16521. /**
  16522. * Get an externaly attached data from its key
  16523. * @param key the unique key that identifies the data
  16524. * @return the associated data, if present (can be null), or undefined if not present
  16525. */
  16526. Engine.prototype.getExternalData = function (key) {
  16527. if (!this._externalData) {
  16528. this._externalData = new BABYLON.StringDictionary();
  16529. }
  16530. return this._externalData.get(key);
  16531. };
  16532. /**
  16533. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16534. * @param key the unique key that identifies the data
  16535. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16536. * @return the associated data, can be null if the factory returned null.
  16537. */
  16538. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16539. if (!this._externalData) {
  16540. this._externalData = new BABYLON.StringDictionary();
  16541. }
  16542. return this._externalData.getOrAddWithFactory(key, factory);
  16543. };
  16544. /**
  16545. * Remove an externaly attached data from the Engine instance
  16546. * @param key the unique key that identifies the data
  16547. * @return true if the data was successfully removed, false if it doesn't exist
  16548. */
  16549. Engine.prototype.removeExternalData = function (key) {
  16550. if (!this._externalData) {
  16551. this._externalData = new BABYLON.StringDictionary();
  16552. }
  16553. return this._externalData.remove(key);
  16554. };
  16555. /**
  16556. * Unbind all vertex attributes from the webGL context
  16557. */
  16558. Engine.prototype.unbindAllAttributes = function () {
  16559. if (this._mustWipeVertexAttributes) {
  16560. this._mustWipeVertexAttributes = false;
  16561. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16562. this._gl.disableVertexAttribArray(i);
  16563. this._vertexAttribArraysEnabled[i] = false;
  16564. this._currentBufferPointers[i].active = false;
  16565. }
  16566. return;
  16567. }
  16568. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16569. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16570. continue;
  16571. }
  16572. this._gl.disableVertexAttribArray(i);
  16573. this._vertexAttribArraysEnabled[i] = false;
  16574. this._currentBufferPointers[i].active = false;
  16575. }
  16576. };
  16577. /**
  16578. * 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
  16579. */
  16580. Engine.prototype.releaseEffects = function () {
  16581. for (var name in this._compiledEffects) {
  16582. this._deleteProgram(this._compiledEffects[name]._program);
  16583. }
  16584. this._compiledEffects = {};
  16585. };
  16586. /**
  16587. * Dispose and release all associated resources
  16588. */
  16589. Engine.prototype.dispose = function () {
  16590. this.hideLoadingUI();
  16591. this.stopRenderLoop();
  16592. // Release postProcesses
  16593. while (this.postProcesses.length) {
  16594. this.postProcesses[0].dispose();
  16595. }
  16596. // Empty texture
  16597. if (this._emptyTexture) {
  16598. this._releaseTexture(this._emptyTexture);
  16599. this._emptyTexture = null;
  16600. }
  16601. if (this._emptyCubeTexture) {
  16602. this._releaseTexture(this._emptyCubeTexture);
  16603. this._emptyCubeTexture = null;
  16604. }
  16605. // Rescale PP
  16606. if (this._rescalePostProcess) {
  16607. this._rescalePostProcess.dispose();
  16608. }
  16609. // Release scenes
  16610. while (this.scenes.length) {
  16611. this.scenes[0].dispose();
  16612. }
  16613. // Release audio engine
  16614. if (Engine.audioEngine) {
  16615. Engine.audioEngine.dispose();
  16616. }
  16617. // Release effects
  16618. this.releaseEffects();
  16619. // Unbind
  16620. this.unbindAllAttributes();
  16621. this._boundUniforms = [];
  16622. if (this._dummyFramebuffer) {
  16623. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16624. }
  16625. //WebVR
  16626. this.disableVR();
  16627. // Events
  16628. if (BABYLON.Tools.IsWindowObjectExist()) {
  16629. window.removeEventListener("blur", this._onBlur);
  16630. window.removeEventListener("focus", this._onFocus);
  16631. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16632. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16633. if (this._renderingCanvas) {
  16634. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16635. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16636. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16637. if (!this._doNotHandleContextLost) {
  16638. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16639. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16640. }
  16641. }
  16642. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16643. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16644. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16645. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16646. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16647. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16648. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16649. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16650. if (this._onVrDisplayConnect) {
  16651. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16652. if (this._onVrDisplayDisconnect) {
  16653. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16654. }
  16655. if (this._onVrDisplayPresentChange) {
  16656. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16657. }
  16658. this._onVrDisplayConnect = null;
  16659. this._onVrDisplayDisconnect = null;
  16660. }
  16661. }
  16662. // Remove from Instances
  16663. var index = Engine.Instances.indexOf(this);
  16664. if (index >= 0) {
  16665. Engine.Instances.splice(index, 1);
  16666. }
  16667. this._workingCanvas = null;
  16668. this._workingContext = null;
  16669. this._currentBufferPointers = [];
  16670. this._renderingCanvas = null;
  16671. this._currentProgram = null;
  16672. this._bindedRenderFunction = null;
  16673. this.onResizeObservable.clear();
  16674. this.onCanvasBlurObservable.clear();
  16675. this.onCanvasFocusObservable.clear();
  16676. this.onCanvasPointerOutObservable.clear();
  16677. this.onBeginFrameObservable.clear();
  16678. this.onEndFrameObservable.clear();
  16679. BABYLON.Effect.ResetCache();
  16680. // Abort active requests
  16681. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16682. var request = _a[_i];
  16683. request.abort();
  16684. }
  16685. };
  16686. // Loading screen
  16687. /**
  16688. * Display the loading screen
  16689. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16690. */
  16691. Engine.prototype.displayLoadingUI = function () {
  16692. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16693. return;
  16694. }
  16695. var loadingScreen = this.loadingScreen;
  16696. if (loadingScreen) {
  16697. loadingScreen.displayLoadingUI();
  16698. }
  16699. };
  16700. /**
  16701. * Hide the loading screen
  16702. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16703. */
  16704. Engine.prototype.hideLoadingUI = function () {
  16705. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16706. return;
  16707. }
  16708. var loadingScreen = this.loadingScreen;
  16709. if (loadingScreen) {
  16710. loadingScreen.hideLoadingUI();
  16711. }
  16712. };
  16713. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16714. /**
  16715. * Gets the current loading screen object
  16716. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16717. */
  16718. get: function () {
  16719. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16720. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16721. return this._loadingScreen;
  16722. },
  16723. /**
  16724. * Sets the current loading screen object
  16725. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16726. */
  16727. set: function (loadingScreen) {
  16728. this._loadingScreen = loadingScreen;
  16729. },
  16730. enumerable: true,
  16731. configurable: true
  16732. });
  16733. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16734. /**
  16735. * Sets the current loading screen text
  16736. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16737. */
  16738. set: function (text) {
  16739. this.loadingScreen.loadingUIText = text;
  16740. },
  16741. enumerable: true,
  16742. configurable: true
  16743. });
  16744. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16745. /**
  16746. * Sets the current loading screen background color
  16747. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16748. */
  16749. set: function (color) {
  16750. this.loadingScreen.loadingUIBackgroundColor = color;
  16751. },
  16752. enumerable: true,
  16753. configurable: true
  16754. });
  16755. /**
  16756. * Attach a new callback raised when context lost event is fired
  16757. * @param callback defines the callback to call
  16758. */
  16759. Engine.prototype.attachContextLostEvent = function (callback) {
  16760. if (this._renderingCanvas) {
  16761. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16762. }
  16763. };
  16764. /**
  16765. * Attach a new callback raised when context restored event is fired
  16766. * @param callback defines the callback to call
  16767. */
  16768. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16769. if (this._renderingCanvas) {
  16770. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16771. }
  16772. };
  16773. /**
  16774. * Gets the source code of the vertex shader associated with a specific webGL program
  16775. * @param program defines the program to use
  16776. * @returns a string containing the source code of the vertex shader associated with the program
  16777. */
  16778. Engine.prototype.getVertexShaderSource = function (program) {
  16779. var shaders = this._gl.getAttachedShaders(program);
  16780. if (!shaders) {
  16781. return null;
  16782. }
  16783. return this._gl.getShaderSource(shaders[0]);
  16784. };
  16785. /**
  16786. * Gets the source code of the fragment shader associated with a specific webGL program
  16787. * @param program defines the program to use
  16788. * @returns a string containing the source code of the fragment shader associated with the program
  16789. */
  16790. Engine.prototype.getFragmentShaderSource = function (program) {
  16791. var shaders = this._gl.getAttachedShaders(program);
  16792. if (!shaders) {
  16793. return null;
  16794. }
  16795. return this._gl.getShaderSource(shaders[1]);
  16796. };
  16797. /**
  16798. * Get the current error code of the webGL context
  16799. * @returns the error code
  16800. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16801. */
  16802. Engine.prototype.getError = function () {
  16803. return this._gl.getError();
  16804. };
  16805. // FPS
  16806. /**
  16807. * Gets the current framerate
  16808. * @returns a number representing the framerate
  16809. */
  16810. Engine.prototype.getFps = function () {
  16811. return this._fps;
  16812. };
  16813. /**
  16814. * Gets the time spent between current and previous frame
  16815. * @returns a number representing the delta time in ms
  16816. */
  16817. Engine.prototype.getDeltaTime = function () {
  16818. return this._deltaTime;
  16819. };
  16820. Engine.prototype._measureFps = function () {
  16821. this._performanceMonitor.sampleFrame();
  16822. this._fps = this._performanceMonitor.averageFPS;
  16823. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16824. };
  16825. /** @hidden */
  16826. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16827. if (faceIndex === void 0) { faceIndex = -1; }
  16828. if (level === void 0) { level = 0; }
  16829. var gl = this._gl;
  16830. if (!this._dummyFramebuffer) {
  16831. var dummy = gl.createFramebuffer();
  16832. if (!dummy) {
  16833. throw new Error("Unable to create dummy framebuffer");
  16834. }
  16835. this._dummyFramebuffer = dummy;
  16836. }
  16837. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16838. if (faceIndex > -1) {
  16839. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16840. }
  16841. else {
  16842. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16843. }
  16844. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16845. var buffer;
  16846. switch (readType) {
  16847. case gl.UNSIGNED_BYTE:
  16848. buffer = new Uint8Array(4 * width * height);
  16849. readType = gl.UNSIGNED_BYTE;
  16850. break;
  16851. default:
  16852. buffer = new Float32Array(4 * width * height);
  16853. readType = gl.FLOAT;
  16854. break;
  16855. }
  16856. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16857. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16858. return buffer;
  16859. };
  16860. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16861. if (this._webGLVersion > 1) {
  16862. return this._caps.colorBufferFloat;
  16863. }
  16864. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16865. };
  16866. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16867. if (this._webGLVersion > 1) {
  16868. return this._caps.colorBufferFloat;
  16869. }
  16870. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16871. };
  16872. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16873. Engine.prototype._canRenderToFramebuffer = function (type) {
  16874. var gl = this._gl;
  16875. //clear existing errors
  16876. while (gl.getError() !== gl.NO_ERROR) { }
  16877. var successful = true;
  16878. var texture = gl.createTexture();
  16879. gl.bindTexture(gl.TEXTURE_2D, texture);
  16880. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16881. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16883. var fb = gl.createFramebuffer();
  16884. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16885. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16886. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16887. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16888. successful = successful && (gl.getError() === gl.NO_ERROR);
  16889. //try render by clearing frame buffer's color buffer
  16890. if (successful) {
  16891. gl.clear(gl.COLOR_BUFFER_BIT);
  16892. successful = successful && (gl.getError() === gl.NO_ERROR);
  16893. }
  16894. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16895. if (successful) {
  16896. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16897. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16898. var readFormat = gl.RGBA;
  16899. var readType = gl.UNSIGNED_BYTE;
  16900. var buffer = new Uint8Array(4);
  16901. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16902. successful = successful && (gl.getError() === gl.NO_ERROR);
  16903. }
  16904. //clean up
  16905. gl.deleteTexture(texture);
  16906. gl.deleteFramebuffer(fb);
  16907. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16908. //clear accumulated errors
  16909. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16910. return successful;
  16911. };
  16912. /** @hidden */
  16913. Engine.prototype._getWebGLTextureType = function (type) {
  16914. if (type === Engine.TEXTURETYPE_FLOAT) {
  16915. return this._gl.FLOAT;
  16916. }
  16917. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16918. // Add Half Float Constant.
  16919. return this._gl.HALF_FLOAT_OES;
  16920. }
  16921. return this._gl.UNSIGNED_BYTE;
  16922. };
  16923. ;
  16924. Engine.prototype._getInternalFormat = function (format) {
  16925. var internalFormat = this._gl.RGBA;
  16926. switch (format) {
  16927. case Engine.TEXTUREFORMAT_ALPHA:
  16928. internalFormat = this._gl.ALPHA;
  16929. break;
  16930. case Engine.TEXTUREFORMAT_LUMINANCE:
  16931. internalFormat = this._gl.LUMINANCE;
  16932. break;
  16933. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16934. internalFormat = this._gl.LUMINANCE_ALPHA;
  16935. break;
  16936. case Engine.TEXTUREFORMAT_RGB:
  16937. internalFormat = this._gl.RGB;
  16938. break;
  16939. case Engine.TEXTUREFORMAT_RGBA:
  16940. internalFormat = this._gl.RGBA;
  16941. break;
  16942. case Engine.TEXTUREFORMAT_R:
  16943. internalFormat = this._gl.RED;
  16944. break;
  16945. case Engine.TEXTUREFORMAT_RG:
  16946. internalFormat = this._gl.RG;
  16947. break;
  16948. }
  16949. return internalFormat;
  16950. };
  16951. /** @hidden */
  16952. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16953. if (this._webGLVersion === 1) {
  16954. if (format !== undefined) {
  16955. switch (format) {
  16956. case Engine.TEXTUREFORMAT_LUMINANCE:
  16957. return this._gl.LUMINANCE;
  16958. case Engine.TEXTUREFORMAT_ALPHA:
  16959. return this._gl.ALPHA;
  16960. }
  16961. }
  16962. return this._gl.RGBA;
  16963. }
  16964. if (type === Engine.TEXTURETYPE_FLOAT) {
  16965. if (format !== undefined) {
  16966. switch (format) {
  16967. case Engine.TEXTUREFORMAT_R:
  16968. return this._gl.R32F;
  16969. case Engine.TEXTUREFORMAT_RG:
  16970. return this._gl.RG32F;
  16971. case Engine.TEXTUREFORMAT_RGB:
  16972. return this._gl.RGB32F;
  16973. }
  16974. }
  16975. return this._gl.RGBA32F;
  16976. }
  16977. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16978. if (format) {
  16979. switch (format) {
  16980. case Engine.TEXTUREFORMAT_R:
  16981. return this._gl.R16F;
  16982. case Engine.TEXTUREFORMAT_RG:
  16983. return this._gl.RG16F;
  16984. case Engine.TEXTUREFORMAT_RGB:
  16985. return this._gl.RGB16F;
  16986. }
  16987. }
  16988. return this._gl.RGBA16F;
  16989. }
  16990. if (format !== undefined) {
  16991. switch (format) {
  16992. case Engine.TEXTUREFORMAT_LUMINANCE:
  16993. return this._gl.LUMINANCE;
  16994. case Engine.TEXTUREFORMAT_RGB:
  16995. return this._gl.RGB;
  16996. case Engine.TEXTUREFORMAT_R:
  16997. return this._gl.R8;
  16998. case Engine.TEXTUREFORMAT_RG:
  16999. return this._gl.RG8;
  17000. case Engine.TEXTUREFORMAT_ALPHA:
  17001. return this._gl.ALPHA;
  17002. }
  17003. }
  17004. return this._gl.RGBA;
  17005. };
  17006. ;
  17007. /** @hidden */
  17008. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17009. if (type === Engine.TEXTURETYPE_FLOAT) {
  17010. return this._gl.RGBA32F;
  17011. }
  17012. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17013. return this._gl.RGBA16F;
  17014. }
  17015. return this._gl.RGBA8;
  17016. };
  17017. ;
  17018. /** @hidden */
  17019. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17020. var _this = this;
  17021. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17022. this._activeRequests.push(request);
  17023. request.onCompleteObservable.add(function (request) {
  17024. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17025. });
  17026. return request;
  17027. };
  17028. /** @hidden */
  17029. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17030. var _this = this;
  17031. return new Promise(function (resolve, reject) {
  17032. _this._loadFile(url, function (data) {
  17033. resolve(data);
  17034. }, undefined, database, useArrayBuffer, function (request, exception) {
  17035. reject(exception);
  17036. });
  17037. });
  17038. };
  17039. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17040. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17041. var onload = function (data) {
  17042. loadedFiles[index] = data;
  17043. loadedFiles._internalCount++;
  17044. if (loadedFiles._internalCount === 6) {
  17045. onfinish(loadedFiles);
  17046. }
  17047. };
  17048. var onerror = function (request, exception) {
  17049. if (onErrorCallBack && request) {
  17050. onErrorCallBack(request.status + " " + request.statusText, exception);
  17051. }
  17052. };
  17053. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17054. };
  17055. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17056. if (onError === void 0) { onError = null; }
  17057. var loadedFiles = [];
  17058. loadedFiles._internalCount = 0;
  17059. for (var index = 0; index < 6; index++) {
  17060. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17061. }
  17062. };
  17063. // Statics
  17064. /**
  17065. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17066. * @returns true if the engine can be created
  17067. * @ignorenaming
  17068. */
  17069. Engine.isSupported = function () {
  17070. try {
  17071. var tempcanvas = document.createElement("canvas");
  17072. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17073. return gl != null && !!window.WebGLRenderingContext;
  17074. }
  17075. catch (e) {
  17076. return false;
  17077. }
  17078. };
  17079. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17080. Engine.ExceptionList = [
  17081. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17082. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17083. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17084. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17085. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17086. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17087. ];
  17088. /** Gets the list of created engines */
  17089. Engine.Instances = new Array();
  17090. /**
  17091. * Hidden
  17092. */
  17093. Engine._TextureLoaders = [];
  17094. // Const statics
  17095. /** Defines that alpha blending is disabled */
  17096. Engine.ALPHA_DISABLE = 0;
  17097. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17098. Engine.ALPHA_ADD = 1;
  17099. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17100. Engine.ALPHA_COMBINE = 2;
  17101. /** Defines that alpha blending to DEST - SRC * DEST */
  17102. Engine.ALPHA_SUBTRACT = 3;
  17103. /** Defines that alpha blending to SRC * DEST */
  17104. Engine.ALPHA_MULTIPLY = 4;
  17105. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17106. Engine.ALPHA_MAXIMIZED = 5;
  17107. /** Defines that alpha blending to SRC + DEST */
  17108. Engine.ALPHA_ONEONE = 6;
  17109. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17110. Engine.ALPHA_PREMULTIPLIED = 7;
  17111. /**
  17112. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17113. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17114. */
  17115. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17116. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17117. Engine.ALPHA_INTERPOLATE = 9;
  17118. /**
  17119. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17120. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17121. */
  17122. Engine.ALPHA_SCREENMODE = 10;
  17123. /** Defines that the ressource is not delayed*/
  17124. Engine.DELAYLOADSTATE_NONE = 0;
  17125. /** Defines that the ressource was successfully delay loaded */
  17126. Engine.DELAYLOADSTATE_LOADED = 1;
  17127. /** Defines that the ressource is currently delay loading */
  17128. Engine.DELAYLOADSTATE_LOADING = 2;
  17129. /** Defines that the ressource is delayed and has not started loading */
  17130. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17131. // Depht or Stencil test Constants.
  17132. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17133. Engine.NEVER = 0x0200;
  17134. /** 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 */
  17135. Engine.ALWAYS = 0x0207;
  17136. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17137. Engine.LESS = 0x0201;
  17138. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17139. Engine.EQUAL = 0x0202;
  17140. /** 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 */
  17141. Engine.LEQUAL = 0x0203;
  17142. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17143. Engine.GREATER = 0x0204;
  17144. /** 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 */
  17145. Engine.GEQUAL = 0x0206;
  17146. /** 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 */
  17147. Engine.NOTEQUAL = 0x0205;
  17148. // Stencil Actions Constants.
  17149. /** Passed to stencilOperation to specify that stencil value must be kept */
  17150. Engine.KEEP = 0x1E00;
  17151. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17152. Engine.REPLACE = 0x1E01;
  17153. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17154. Engine.INCR = 0x1E02;
  17155. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17156. Engine.DECR = 0x1E03;
  17157. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17158. Engine.INVERT = 0x150A;
  17159. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17160. Engine.INCR_WRAP = 0x8507;
  17161. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17162. Engine.DECR_WRAP = 0x8508;
  17163. /** Texture is not repeating outside of 0..1 UVs */
  17164. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17165. /** Texture is repeating outside of 0..1 UVs */
  17166. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17167. /** Texture is repeating and mirrored */
  17168. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17169. /** ALPHA */
  17170. Engine.TEXTUREFORMAT_ALPHA = 0;
  17171. /** LUMINANCE */
  17172. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17173. /** LUMINANCE_ALPHA */
  17174. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17175. /** RGB */
  17176. Engine.TEXTUREFORMAT_RGB = 4;
  17177. /** RGBA */
  17178. Engine.TEXTUREFORMAT_RGBA = 5;
  17179. /** R */
  17180. Engine.TEXTUREFORMAT_R = 6;
  17181. /** RG */
  17182. Engine.TEXTUREFORMAT_RG = 7;
  17183. /** UNSIGNED_INT */
  17184. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17185. /** FLOAT */
  17186. Engine.TEXTURETYPE_FLOAT = 1;
  17187. /** HALF_FLOAT */
  17188. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17189. /** nearest is mag = nearest and min = nearest and mip = linear */
  17190. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17191. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17192. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17193. /** Trilinear is mag = linear and min = linear and mip = linear */
  17194. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17195. /** nearest is mag = nearest and min = nearest and mip = linear */
  17196. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17197. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17198. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17199. /** Trilinear is mag = linear and min = linear and mip = linear */
  17200. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17201. /** mag = nearest and min = nearest and mip = nearest */
  17202. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17203. /** mag = nearest and min = linear and mip = nearest */
  17204. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17205. /** mag = nearest and min = linear and mip = linear */
  17206. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17207. /** mag = nearest and min = linear and mip = none */
  17208. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17209. /** mag = nearest and min = nearest and mip = none */
  17210. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17211. /** mag = linear and min = nearest and mip = nearest */
  17212. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17213. /** mag = linear and min = nearest and mip = linear */
  17214. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17215. /** mag = linear and min = linear and mip = none */
  17216. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17217. /** mag = linear and min = nearest and mip = none */
  17218. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17219. /** Explicit coordinates mode */
  17220. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17221. /** Spherical coordinates mode */
  17222. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17223. /** Planar coordinates mode */
  17224. Engine.TEXTURE_PLANAR_MODE = 2;
  17225. /** Cubic coordinates mode */
  17226. Engine.TEXTURE_CUBIC_MODE = 3;
  17227. /** Projection coordinates mode */
  17228. Engine.TEXTURE_PROJECTION_MODE = 4;
  17229. /** Skybox coordinates mode */
  17230. Engine.TEXTURE_SKYBOX_MODE = 5;
  17231. /** Inverse Cubic coordinates mode */
  17232. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17233. /** Equirectangular coordinates mode */
  17234. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17235. /** Equirectangular Fixed coordinates mode */
  17236. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17237. /** Equirectangular Fixed Mirrored coordinates mode */
  17238. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17239. // Texture rescaling mode
  17240. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17241. Engine.SCALEMODE_FLOOR = 1;
  17242. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17243. Engine.SCALEMODE_NEAREST = 2;
  17244. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17245. Engine.SCALEMODE_CEILING = 3;
  17246. // Updatable statics so stick with vars here
  17247. /**
  17248. * Gets or sets the epsilon value used by collision engine
  17249. */
  17250. Engine.CollisionsEpsilon = 0.001;
  17251. /**
  17252. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17253. */
  17254. Engine.CodeRepository = "src/";
  17255. /**
  17256. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17257. */
  17258. Engine.ShadersRepository = "src/Shaders/";
  17259. return Engine;
  17260. }());
  17261. BABYLON.Engine = Engine;
  17262. })(BABYLON || (BABYLON = {}));
  17263. //# sourceMappingURL=babylon.engine.js.map
  17264. var BABYLON;
  17265. (function (BABYLON) {
  17266. /**
  17267. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17268. */
  17269. var Node = /** @class */ (function () {
  17270. /**
  17271. * Creates a new Node
  17272. * @param {string} name - the name and id to be given to this node
  17273. * @param {BABYLON.Scene} the scene this node will be added to
  17274. */
  17275. function Node(name, scene) {
  17276. if (scene === void 0) { scene = null; }
  17277. /**
  17278. * Gets or sets a string used to store user defined state for the node
  17279. */
  17280. this.state = "";
  17281. /**
  17282. * Gets or sets an object used to store user defined information for the node
  17283. */
  17284. this.metadata = null;
  17285. /**
  17286. * Gets or sets a boolean used to define if the node must be serialized
  17287. */
  17288. this.doNotSerialize = false;
  17289. /** @hidden */
  17290. this._isDisposed = false;
  17291. /**
  17292. * Gets a list of Animations associated with the node
  17293. */
  17294. this.animations = new Array();
  17295. this._ranges = {};
  17296. this._isEnabled = true;
  17297. this._isReady = true;
  17298. /** @hidden */
  17299. this._currentRenderId = -1;
  17300. this._parentRenderId = -1;
  17301. this._childRenderId = -1;
  17302. this._animationPropertiesOverride = null;
  17303. /**
  17304. * An event triggered when the mesh is disposed
  17305. */
  17306. this.onDisposeObservable = new BABYLON.Observable();
  17307. // Behaviors
  17308. this._behaviors = new Array();
  17309. this.name = name;
  17310. this.id = name;
  17311. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17312. this.uniqueId = this._scene.getUniqueId();
  17313. this._initCache();
  17314. }
  17315. /**
  17316. * Add a new node constructor
  17317. * @param type defines the type name of the node to construct
  17318. * @param constructorFunc defines the constructor function
  17319. */
  17320. Node.AddNodeConstructor = function (type, constructorFunc) {
  17321. this._NodeConstructors[type] = constructorFunc;
  17322. };
  17323. /**
  17324. * Returns a node constructor based on type name
  17325. * @param type defines the type name
  17326. * @param name defines the new node name
  17327. * @param scene defines the hosting scene
  17328. * @param options defines optional options to transmit to constructors
  17329. * @returns the new constructor or null
  17330. */
  17331. Node.Construct = function (type, name, scene, options) {
  17332. var constructorFunc = this._NodeConstructors[type];
  17333. if (!constructorFunc) {
  17334. return null;
  17335. }
  17336. return constructorFunc(name, scene, options);
  17337. };
  17338. /**
  17339. * Gets a boolean indicating if the node has been disposed
  17340. * @returns true if the node was disposed
  17341. */
  17342. Node.prototype.isDisposed = function () {
  17343. return this._isDisposed;
  17344. };
  17345. Object.defineProperty(Node.prototype, "parent", {
  17346. get: function () {
  17347. return this._parentNode;
  17348. },
  17349. /**
  17350. * Gets or sets the parent of the node
  17351. */
  17352. set: function (parent) {
  17353. if (this._parentNode === parent) {
  17354. return;
  17355. }
  17356. // Remove self from list of children of parent
  17357. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17358. var index = this._parentNode._children.indexOf(this);
  17359. if (index !== -1) {
  17360. this._parentNode._children.splice(index, 1);
  17361. }
  17362. }
  17363. // Store new parent
  17364. this._parentNode = parent;
  17365. // Add as child to new parent
  17366. if (this._parentNode) {
  17367. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17368. this._parentNode._children = new Array();
  17369. }
  17370. this._parentNode._children.push(this);
  17371. }
  17372. },
  17373. enumerable: true,
  17374. configurable: true
  17375. });
  17376. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17377. /**
  17378. * Gets or sets the animation properties override
  17379. */
  17380. get: function () {
  17381. if (!this._animationPropertiesOverride) {
  17382. return this._scene.animationPropertiesOverride;
  17383. }
  17384. return this._animationPropertiesOverride;
  17385. },
  17386. set: function (value) {
  17387. this._animationPropertiesOverride = value;
  17388. },
  17389. enumerable: true,
  17390. configurable: true
  17391. });
  17392. /**
  17393. * Gets a string idenfifying the name of the class
  17394. * @returns "Node" string
  17395. */
  17396. Node.prototype.getClassName = function () {
  17397. return "Node";
  17398. };
  17399. Object.defineProperty(Node.prototype, "onDispose", {
  17400. /**
  17401. * Sets a callback that will be raised when the node will be disposed
  17402. */
  17403. set: function (callback) {
  17404. if (this._onDisposeObserver) {
  17405. this.onDisposeObservable.remove(this._onDisposeObserver);
  17406. }
  17407. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17408. },
  17409. enumerable: true,
  17410. configurable: true
  17411. });
  17412. /**
  17413. * Gets the scene of the node
  17414. * @returns a {BABYLON.Scene}
  17415. */
  17416. Node.prototype.getScene = function () {
  17417. return this._scene;
  17418. };
  17419. /**
  17420. * Gets the engine of the node
  17421. * @returns a {BABYLON.Engine}
  17422. */
  17423. Node.prototype.getEngine = function () {
  17424. return this._scene.getEngine();
  17425. };
  17426. /**
  17427. * Attach a behavior to the node
  17428. * @see http://doc.babylonjs.com/features/behaviour
  17429. * @param behavior defines the behavior to attach
  17430. * @returns the current Node
  17431. */
  17432. Node.prototype.addBehavior = function (behavior) {
  17433. var _this = this;
  17434. var index = this._behaviors.indexOf(behavior);
  17435. if (index !== -1) {
  17436. return this;
  17437. }
  17438. behavior.init();
  17439. if (this._scene.isLoading) {
  17440. // We defer the attach when the scene will be loaded
  17441. this._scene.onDataLoadedObservable.addOnce(function () {
  17442. behavior.attach(_this);
  17443. });
  17444. }
  17445. else {
  17446. behavior.attach(this);
  17447. }
  17448. this._behaviors.push(behavior);
  17449. return this;
  17450. };
  17451. /**
  17452. * Remove an attached behavior
  17453. * @see http://doc.babylonjs.com/features/behaviour
  17454. * @param behavior defines the behavior to attach
  17455. * @returns the current Node
  17456. */
  17457. Node.prototype.removeBehavior = function (behavior) {
  17458. var index = this._behaviors.indexOf(behavior);
  17459. if (index === -1) {
  17460. return this;
  17461. }
  17462. this._behaviors[index].detach();
  17463. this._behaviors.splice(index, 1);
  17464. return this;
  17465. };
  17466. Object.defineProperty(Node.prototype, "behaviors", {
  17467. /**
  17468. * Gets the list of attached behaviors
  17469. * @see http://doc.babylonjs.com/features/behaviour
  17470. */
  17471. get: function () {
  17472. return this._behaviors;
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. /**
  17478. * Gets an attached behavior by name
  17479. * @param name defines the name of the behavior to look for
  17480. * @see http://doc.babylonjs.com/features/behaviour
  17481. * @returns null if behavior was not found else the requested behavior
  17482. */
  17483. Node.prototype.getBehaviorByName = function (name) {
  17484. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17485. var behavior = _a[_i];
  17486. if (behavior.name === name) {
  17487. return behavior;
  17488. }
  17489. }
  17490. return null;
  17491. };
  17492. /**
  17493. * Returns the world matrix of the node
  17494. * @returns a matrix containing the node's world matrix
  17495. */
  17496. Node.prototype.getWorldMatrix = function () {
  17497. return BABYLON.Matrix.Identity();
  17498. };
  17499. /** @hidden */
  17500. Node.prototype._getWorldMatrixDeterminant = function () {
  17501. return 1;
  17502. };
  17503. // override it in derived class if you add new variables to the cache
  17504. // and call the parent class method
  17505. /** @hidden */
  17506. Node.prototype._initCache = function () {
  17507. this._cache = {};
  17508. this._cache.parent = undefined;
  17509. };
  17510. /** @hidden */
  17511. Node.prototype.updateCache = function (force) {
  17512. if (!force && this.isSynchronized())
  17513. return;
  17514. this._cache.parent = this.parent;
  17515. this._updateCache();
  17516. };
  17517. // override it in derived class if you add new variables to the cache
  17518. // and call the parent class method if !ignoreParentClass
  17519. /** @hidden */
  17520. Node.prototype._updateCache = function (ignoreParentClass) {
  17521. };
  17522. // override it in derived class if you add new variables to the cache
  17523. /** @hidden */
  17524. Node.prototype._isSynchronized = function () {
  17525. return true;
  17526. };
  17527. /** @hidden */
  17528. Node.prototype._markSyncedWithParent = function () {
  17529. if (this.parent) {
  17530. this._parentRenderId = this.parent._childRenderId;
  17531. }
  17532. };
  17533. /** @hidden */
  17534. Node.prototype.isSynchronizedWithParent = function () {
  17535. if (!this.parent) {
  17536. return true;
  17537. }
  17538. if (this._parentRenderId !== this.parent._childRenderId) {
  17539. return false;
  17540. }
  17541. return this.parent.isSynchronized();
  17542. };
  17543. /** @hidden */
  17544. Node.prototype.isSynchronized = function (updateCache) {
  17545. var check = this.hasNewParent();
  17546. check = check || !this.isSynchronizedWithParent();
  17547. check = check || !this._isSynchronized();
  17548. if (updateCache)
  17549. this.updateCache(true);
  17550. return !check;
  17551. };
  17552. /** @hidden */
  17553. Node.prototype.hasNewParent = function (update) {
  17554. if (this._cache.parent === this.parent)
  17555. return false;
  17556. if (update)
  17557. this._cache.parent = this.parent;
  17558. return true;
  17559. };
  17560. /**
  17561. * Is this node ready to be used/rendered
  17562. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17563. * @return true if the node is ready
  17564. */
  17565. Node.prototype.isReady = function (completeCheck) {
  17566. if (completeCheck === void 0) { completeCheck = false; }
  17567. return this._isReady;
  17568. };
  17569. /**
  17570. * Is this node enabled?
  17571. * 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
  17572. * @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
  17573. * @return whether this node (and its parent) is enabled
  17574. */
  17575. Node.prototype.isEnabled = function (checkAncestors) {
  17576. if (checkAncestors === void 0) { checkAncestors = true; }
  17577. if (checkAncestors === false) {
  17578. return this._isEnabled;
  17579. }
  17580. if (this._isEnabled === false) {
  17581. return false;
  17582. }
  17583. if (this.parent !== undefined && this.parent !== null) {
  17584. return this.parent.isEnabled(checkAncestors);
  17585. }
  17586. return true;
  17587. };
  17588. /**
  17589. * Set the enabled state of this node
  17590. * @param value defines the new enabled state
  17591. */
  17592. Node.prototype.setEnabled = function (value) {
  17593. this._isEnabled = value;
  17594. };
  17595. /**
  17596. * Is this node a descendant of the given node?
  17597. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17598. * @param ancestor defines the parent node to inspect
  17599. * @returns a boolean indicating if this node is a descendant of the given node
  17600. */
  17601. Node.prototype.isDescendantOf = function (ancestor) {
  17602. if (this.parent) {
  17603. if (this.parent === ancestor) {
  17604. return true;
  17605. }
  17606. return this.parent.isDescendantOf(ancestor);
  17607. }
  17608. return false;
  17609. };
  17610. /** @hidden */
  17611. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17612. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17613. if (!this._children) {
  17614. return;
  17615. }
  17616. for (var index = 0; index < this._children.length; index++) {
  17617. var item = this._children[index];
  17618. if (!predicate || predicate(item)) {
  17619. results.push(item);
  17620. }
  17621. if (!directDescendantsOnly) {
  17622. item._getDescendants(results, false, predicate);
  17623. }
  17624. }
  17625. };
  17626. /**
  17627. * Will return all nodes that have this node as ascendant
  17628. * @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
  17629. * @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
  17630. * @return all children nodes of all types
  17631. */
  17632. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17633. var results = new Array();
  17634. this._getDescendants(results, directDescendantsOnly, predicate);
  17635. return results;
  17636. };
  17637. /**
  17638. * Get all child-meshes of this node
  17639. * @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
  17640. * @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
  17641. * @returns an array of {BABYLON.AbstractMesh}
  17642. */
  17643. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17644. var results = [];
  17645. this._getDescendants(results, directDescendantsOnly, function (node) {
  17646. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17647. });
  17648. return results;
  17649. };
  17650. /**
  17651. * Get all child-transformNodes of this node
  17652. * @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
  17653. * @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
  17654. * @returns an array of {BABYLON.TransformNode}
  17655. */
  17656. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17657. var results = [];
  17658. this._getDescendants(results, directDescendantsOnly, function (node) {
  17659. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17660. });
  17661. return results;
  17662. };
  17663. /**
  17664. * Get all direct children of this node
  17665. * @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
  17666. * @returns an array of {BABYLON.Node}
  17667. */
  17668. Node.prototype.getChildren = function (predicate) {
  17669. return this.getDescendants(true, predicate);
  17670. };
  17671. /** @hidden */
  17672. Node.prototype._setReady = function (state) {
  17673. if (state === this._isReady) {
  17674. return;
  17675. }
  17676. if (!state) {
  17677. this._isReady = false;
  17678. return;
  17679. }
  17680. if (this.onReady) {
  17681. this.onReady(this);
  17682. }
  17683. this._isReady = true;
  17684. };
  17685. /**
  17686. * Get an animation by name
  17687. * @param name defines the name of the animation to look for
  17688. * @returns null if not found else the requested animation
  17689. */
  17690. Node.prototype.getAnimationByName = function (name) {
  17691. for (var i = 0; i < this.animations.length; i++) {
  17692. var animation = this.animations[i];
  17693. if (animation.name === name) {
  17694. return animation;
  17695. }
  17696. }
  17697. return null;
  17698. };
  17699. /**
  17700. * Creates an animation range for this node
  17701. * @param name defines the name of the range
  17702. * @param from defines the starting key
  17703. * @param to defines the end key
  17704. */
  17705. Node.prototype.createAnimationRange = function (name, from, to) {
  17706. // check name not already in use
  17707. if (!this._ranges[name]) {
  17708. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17709. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17710. if (this.animations[i]) {
  17711. this.animations[i].createRange(name, from, to);
  17712. }
  17713. }
  17714. }
  17715. };
  17716. /**
  17717. * Delete a specific animation range
  17718. * @param name defines the name of the range to delete
  17719. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17720. */
  17721. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17722. if (deleteFrames === void 0) { deleteFrames = true; }
  17723. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17724. if (this.animations[i]) {
  17725. this.animations[i].deleteRange(name, deleteFrames);
  17726. }
  17727. }
  17728. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17729. };
  17730. /**
  17731. * Get an animation range by name
  17732. * @param name defines the name of the animation range to look for
  17733. * @returns null if not found else the requested animation range
  17734. */
  17735. Node.prototype.getAnimationRange = function (name) {
  17736. return this._ranges[name];
  17737. };
  17738. /**
  17739. * Will start the animation sequence
  17740. * @param name defines the range frames for animation sequence
  17741. * @param loop defines if the animation should loop (false by default)
  17742. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17743. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17744. * @returns the object created for this animation. If range does not exist, it will return null
  17745. */
  17746. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17747. var range = this.getAnimationRange(name);
  17748. if (!range) {
  17749. return null;
  17750. }
  17751. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17752. };
  17753. /**
  17754. * Serialize animation ranges into a JSON compatible object
  17755. * @returns serialization object
  17756. */
  17757. Node.prototype.serializeAnimationRanges = function () {
  17758. var serializationRanges = [];
  17759. for (var name in this._ranges) {
  17760. var localRange = this._ranges[name];
  17761. if (!localRange) {
  17762. continue;
  17763. }
  17764. var range = {};
  17765. range.name = name;
  17766. range.from = localRange.from;
  17767. range.to = localRange.to;
  17768. serializationRanges.push(range);
  17769. }
  17770. return serializationRanges;
  17771. };
  17772. /**
  17773. * Computes the world matrix of the node
  17774. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17775. * @returns the world matrix
  17776. */
  17777. Node.prototype.computeWorldMatrix = function (force) {
  17778. return BABYLON.Matrix.Identity();
  17779. };
  17780. /**
  17781. * Releases resources associated with this node.
  17782. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17783. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17784. */
  17785. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17786. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17787. if (!doNotRecurse) {
  17788. var nodes = this.getDescendants(true);
  17789. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17790. var node = nodes_1[_i];
  17791. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17792. }
  17793. }
  17794. else {
  17795. var transformNodes = this.getChildTransformNodes(true);
  17796. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17797. var transformNode = transformNodes_1[_a];
  17798. transformNode.parent = null;
  17799. transformNode.computeWorldMatrix(true);
  17800. }
  17801. }
  17802. this.parent = null;
  17803. // Callback
  17804. this.onDisposeObservable.notifyObservers(this);
  17805. this.onDisposeObservable.clear();
  17806. // Behaviors
  17807. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17808. var behavior = _c[_b];
  17809. behavior.detach();
  17810. }
  17811. this._behaviors = [];
  17812. this._isDisposed = true;
  17813. };
  17814. /**
  17815. * Parse animation range data from a serialization object and store them into a given node
  17816. * @param node defines where to store the animation ranges
  17817. * @param parsedNode defines the serialization object to read data from
  17818. * @param scene defines the hosting scene
  17819. */
  17820. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17821. if (parsedNode.ranges) {
  17822. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17823. var data = parsedNode.ranges[index];
  17824. node.createAnimationRange(data.name, data.from, data.to);
  17825. }
  17826. }
  17827. };
  17828. Node._NodeConstructors = {};
  17829. __decorate([
  17830. BABYLON.serialize()
  17831. ], Node.prototype, "name", void 0);
  17832. __decorate([
  17833. BABYLON.serialize()
  17834. ], Node.prototype, "id", void 0);
  17835. __decorate([
  17836. BABYLON.serialize()
  17837. ], Node.prototype, "uniqueId", void 0);
  17838. __decorate([
  17839. BABYLON.serialize()
  17840. ], Node.prototype, "state", void 0);
  17841. __decorate([
  17842. BABYLON.serialize()
  17843. ], Node.prototype, "metadata", void 0);
  17844. return Node;
  17845. }());
  17846. BABYLON.Node = Node;
  17847. })(BABYLON || (BABYLON = {}));
  17848. //# sourceMappingURL=babylon.node.js.map
  17849. var BABYLON;
  17850. (function (BABYLON) {
  17851. var BoundingSphere = /** @class */ (function () {
  17852. /**
  17853. * Creates a new bounding sphere
  17854. * @param min defines the minimum vector (in local space)
  17855. * @param max defines the maximum vector (in local space)
  17856. */
  17857. function BoundingSphere(min, max) {
  17858. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17859. this.reConstruct(min, max);
  17860. }
  17861. /**
  17862. * Recreates the entire bounding sphere from scratch
  17863. * @param min defines the new minimum vector (in local space)
  17864. * @param max defines the new maximum vector (in local space)
  17865. */
  17866. BoundingSphere.prototype.reConstruct = function (min, max) {
  17867. this.minimum = min.clone();
  17868. this.maximum = max.clone();
  17869. var distance = BABYLON.Vector3.Distance(min, max);
  17870. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17871. this.radius = distance * 0.5;
  17872. this.centerWorld = BABYLON.Vector3.Zero();
  17873. this._update(BABYLON.Matrix.Identity());
  17874. };
  17875. /**
  17876. * Scale the current bounding sphere by applying a scale factor
  17877. * @param factor defines the scale factor to apply
  17878. * @returns the current bounding box
  17879. */
  17880. BoundingSphere.prototype.scale = function (factor) {
  17881. var newRadius = this.radius * factor;
  17882. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17883. var min = this.center.subtract(newRadiusVector);
  17884. var max = this.center.add(newRadiusVector);
  17885. this.reConstruct(min, max);
  17886. return this;
  17887. };
  17888. // Methods
  17889. BoundingSphere.prototype._update = function (world) {
  17890. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17891. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17892. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17893. };
  17894. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17895. for (var i = 0; i < 6; i++) {
  17896. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17897. return false;
  17898. }
  17899. return true;
  17900. };
  17901. BoundingSphere.prototype.intersectsPoint = function (point) {
  17902. var x = this.centerWorld.x - point.x;
  17903. var y = this.centerWorld.y - point.y;
  17904. var z = this.centerWorld.z - point.z;
  17905. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17906. if (this.radiusWorld < distance)
  17907. return false;
  17908. return true;
  17909. };
  17910. // Statics
  17911. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17912. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17913. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17914. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17915. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17916. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17917. return false;
  17918. return true;
  17919. };
  17920. return BoundingSphere;
  17921. }());
  17922. BABYLON.BoundingSphere = BoundingSphere;
  17923. })(BABYLON || (BABYLON = {}));
  17924. //# sourceMappingURL=babylon.boundingSphere.js.map
  17925. var BABYLON;
  17926. (function (BABYLON) {
  17927. var BoundingBox = /** @class */ (function () {
  17928. /**
  17929. * Creates a new bounding box
  17930. * @param min defines the minimum vector (in local space)
  17931. * @param max defines the maximum vector (in local space)
  17932. */
  17933. function BoundingBox(min, max) {
  17934. this.vectorsWorld = new Array();
  17935. this.reConstruct(min, max);
  17936. }
  17937. // Methods
  17938. /**
  17939. * Recreates the entire bounding box from scratch
  17940. * @param min defines the new minimum vector (in local space)
  17941. * @param max defines the new maximum vector (in local space)
  17942. */
  17943. BoundingBox.prototype.reConstruct = function (min, max) {
  17944. this.minimum = min.clone();
  17945. this.maximum = max.clone();
  17946. // Bounding vectors
  17947. this.vectors = new Array();
  17948. this.vectors.push(this.minimum.clone());
  17949. this.vectors.push(this.maximum.clone());
  17950. this.vectors.push(this.minimum.clone());
  17951. this.vectors[2].x = this.maximum.x;
  17952. this.vectors.push(this.minimum.clone());
  17953. this.vectors[3].y = this.maximum.y;
  17954. this.vectors.push(this.minimum.clone());
  17955. this.vectors[4].z = this.maximum.z;
  17956. this.vectors.push(this.maximum.clone());
  17957. this.vectors[5].z = this.minimum.z;
  17958. this.vectors.push(this.maximum.clone());
  17959. this.vectors[6].x = this.minimum.x;
  17960. this.vectors.push(this.maximum.clone());
  17961. this.vectors[7].y = this.minimum.y;
  17962. // OBB
  17963. this.center = this.maximum.add(this.minimum).scale(0.5);
  17964. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17965. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17966. // World
  17967. for (var index = 0; index < this.vectors.length; index++) {
  17968. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17969. }
  17970. this.minimumWorld = BABYLON.Vector3.Zero();
  17971. this.maximumWorld = BABYLON.Vector3.Zero();
  17972. this.centerWorld = BABYLON.Vector3.Zero();
  17973. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17974. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17975. };
  17976. /**
  17977. * Scale the current bounding box by applying a scale factor
  17978. * @param factor defines the scale factor to apply
  17979. * @returns the current bounding box
  17980. */
  17981. BoundingBox.prototype.scale = function (factor) {
  17982. var diff = this.maximum.subtract(this.minimum);
  17983. var distance = diff.length() * factor;
  17984. diff.normalize();
  17985. var newRadius = diff.scale(distance / 2);
  17986. var min = this.center.subtract(newRadius);
  17987. var max = this.center.add(newRadius);
  17988. this.reConstruct(min, max);
  17989. return this;
  17990. };
  17991. BoundingBox.prototype.getWorldMatrix = function () {
  17992. return this._worldMatrix;
  17993. };
  17994. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17995. this._worldMatrix.copyFrom(matrix);
  17996. return this;
  17997. };
  17998. BoundingBox.prototype._update = function (world) {
  17999. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18000. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18001. for (var index = 0; index < this.vectors.length; index++) {
  18002. var v = this.vectorsWorld[index];
  18003. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18004. if (v.x < this.minimumWorld.x)
  18005. this.minimumWorld.x = v.x;
  18006. if (v.y < this.minimumWorld.y)
  18007. this.minimumWorld.y = v.y;
  18008. if (v.z < this.minimumWorld.z)
  18009. this.minimumWorld.z = v.z;
  18010. if (v.x > this.maximumWorld.x)
  18011. this.maximumWorld.x = v.x;
  18012. if (v.y > this.maximumWorld.y)
  18013. this.maximumWorld.y = v.y;
  18014. if (v.z > this.maximumWorld.z)
  18015. this.maximumWorld.z = v.z;
  18016. }
  18017. // Extend
  18018. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18019. this.extendSizeWorld.scaleInPlace(0.5);
  18020. // OBB
  18021. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18022. this.centerWorld.scaleInPlace(0.5);
  18023. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18024. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18025. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18026. this._worldMatrix = world;
  18027. };
  18028. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18029. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18030. };
  18031. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18032. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18033. };
  18034. BoundingBox.prototype.intersectsPoint = function (point) {
  18035. var delta = -BABYLON.Epsilon;
  18036. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18037. return false;
  18038. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18039. return false;
  18040. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18041. return false;
  18042. return true;
  18043. };
  18044. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18045. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18046. };
  18047. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18048. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18049. return false;
  18050. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18051. return false;
  18052. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18053. return false;
  18054. return true;
  18055. };
  18056. // Statics
  18057. BoundingBox.Intersects = function (box0, box1) {
  18058. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18059. return false;
  18060. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18061. return false;
  18062. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18063. return false;
  18064. return true;
  18065. };
  18066. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18067. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18068. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18069. return (num <= (sphereRadius * sphereRadius));
  18070. };
  18071. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18072. for (var p = 0; p < 6; p++) {
  18073. for (var i = 0; i < 8; i++) {
  18074. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18075. return false;
  18076. }
  18077. }
  18078. }
  18079. return true;
  18080. };
  18081. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18082. for (var p = 0; p < 6; p++) {
  18083. var inCount = 8;
  18084. for (var i = 0; i < 8; i++) {
  18085. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18086. --inCount;
  18087. }
  18088. else {
  18089. break;
  18090. }
  18091. }
  18092. if (inCount === 0)
  18093. return false;
  18094. }
  18095. return true;
  18096. };
  18097. return BoundingBox;
  18098. }());
  18099. BABYLON.BoundingBox = BoundingBox;
  18100. })(BABYLON || (BABYLON = {}));
  18101. //# sourceMappingURL=babylon.boundingBox.js.map
  18102. var BABYLON;
  18103. (function (BABYLON) {
  18104. var computeBoxExtents = function (axis, box) {
  18105. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18106. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18107. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18108. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18109. var r = r0 + r1 + r2;
  18110. return {
  18111. min: p - r,
  18112. max: p + r
  18113. };
  18114. };
  18115. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18116. var axisOverlap = function (axis, box0, box1) {
  18117. var result0 = computeBoxExtents(axis, box0);
  18118. var result1 = computeBoxExtents(axis, box1);
  18119. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18120. };
  18121. var BoundingInfo = /** @class */ (function () {
  18122. function BoundingInfo(minimum, maximum) {
  18123. this.minimum = minimum;
  18124. this.maximum = maximum;
  18125. this._isLocked = false;
  18126. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18127. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18128. }
  18129. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18130. get: function () {
  18131. return this._isLocked;
  18132. },
  18133. set: function (value) {
  18134. this._isLocked = value;
  18135. },
  18136. enumerable: true,
  18137. configurable: true
  18138. });
  18139. // Methods
  18140. BoundingInfo.prototype.update = function (world) {
  18141. if (this._isLocked) {
  18142. return;
  18143. }
  18144. this.boundingBox._update(world);
  18145. this.boundingSphere._update(world);
  18146. };
  18147. /**
  18148. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18149. * @param center New center of the bounding info
  18150. * @param extend New extend of the bounding info
  18151. */
  18152. BoundingInfo.prototype.centerOn = function (center, extend) {
  18153. this.minimum = center.subtract(extend);
  18154. this.maximum = center.add(extend);
  18155. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18156. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18157. return this;
  18158. };
  18159. /**
  18160. * Scale the current bounding info by applying a scale factor
  18161. * @param factor defines the scale factor to apply
  18162. * @returns the current bounding info
  18163. */
  18164. BoundingInfo.prototype.scale = function (factor) {
  18165. this.boundingBox.scale(factor);
  18166. this.boundingSphere.scale(factor);
  18167. return this;
  18168. };
  18169. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18170. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18171. return false;
  18172. return this.boundingBox.isInFrustum(frustumPlanes);
  18173. };
  18174. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18175. /**
  18176. * Gets the world distance between the min and max points of the bounding box
  18177. */
  18178. get: function () {
  18179. var boundingBox = this.boundingBox;
  18180. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18181. return size.length();
  18182. },
  18183. enumerable: true,
  18184. configurable: true
  18185. });
  18186. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18187. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18188. };
  18189. BoundingInfo.prototype._checkCollision = function (collider) {
  18190. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18191. };
  18192. BoundingInfo.prototype.intersectsPoint = function (point) {
  18193. if (!this.boundingSphere.centerWorld) {
  18194. return false;
  18195. }
  18196. if (!this.boundingSphere.intersectsPoint(point)) {
  18197. return false;
  18198. }
  18199. if (!this.boundingBox.intersectsPoint(point)) {
  18200. return false;
  18201. }
  18202. return true;
  18203. };
  18204. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18205. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18206. return false;
  18207. }
  18208. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18209. return false;
  18210. }
  18211. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18212. return false;
  18213. }
  18214. if (!precise) {
  18215. return true;
  18216. }
  18217. var box0 = this.boundingBox;
  18218. var box1 = boundingInfo.boundingBox;
  18219. if (!axisOverlap(box0.directions[0], box0, box1))
  18220. return false;
  18221. if (!axisOverlap(box0.directions[1], box0, box1))
  18222. return false;
  18223. if (!axisOverlap(box0.directions[2], box0, box1))
  18224. return false;
  18225. if (!axisOverlap(box1.directions[0], box0, box1))
  18226. return false;
  18227. if (!axisOverlap(box1.directions[1], box0, box1))
  18228. return false;
  18229. if (!axisOverlap(box1.directions[2], box0, box1))
  18230. return false;
  18231. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18232. return false;
  18233. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18234. return false;
  18235. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18236. return false;
  18237. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18238. return false;
  18239. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18240. return false;
  18241. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18242. return false;
  18243. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18244. return false;
  18245. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18246. return false;
  18247. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18248. return false;
  18249. return true;
  18250. };
  18251. return BoundingInfo;
  18252. }());
  18253. BABYLON.BoundingInfo = BoundingInfo;
  18254. })(BABYLON || (BABYLON = {}));
  18255. //# sourceMappingURL=babylon.boundingInfo.js.map
  18256. var BABYLON;
  18257. (function (BABYLON) {
  18258. var TransformNode = /** @class */ (function (_super) {
  18259. __extends(TransformNode, _super);
  18260. function TransformNode(name, scene, isPure) {
  18261. if (scene === void 0) { scene = null; }
  18262. if (isPure === void 0) { isPure = true; }
  18263. var _this = _super.call(this, name, scene) || this;
  18264. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18265. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18266. _this._up = new BABYLON.Vector3(0, 1, 0);
  18267. _this._right = new BABYLON.Vector3(1, 0, 0);
  18268. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18269. // Properties
  18270. _this._rotation = BABYLON.Vector3.Zero();
  18271. _this._scaling = BABYLON.Vector3.One();
  18272. _this._isDirty = false;
  18273. /**
  18274. * Set the billboard mode. Default is 0.
  18275. *
  18276. * | Value | Type | Description |
  18277. * | --- | --- | --- |
  18278. * | 0 | BILLBOARDMODE_NONE | |
  18279. * | 1 | BILLBOARDMODE_X | |
  18280. * | 2 | BILLBOARDMODE_Y | |
  18281. * | 4 | BILLBOARDMODE_Z | |
  18282. * | 7 | BILLBOARDMODE_ALL | |
  18283. *
  18284. */
  18285. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18286. _this.scalingDeterminant = 1;
  18287. _this.infiniteDistance = false;
  18288. /**
  18289. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18290. * By default the system will update normals to compensate
  18291. */
  18292. _this.ignoreNonUniformScaling = false;
  18293. _this.position = BABYLON.Vector3.Zero();
  18294. _this._localWorld = BABYLON.Matrix.Zero();
  18295. _this._worldMatrix = BABYLON.Matrix.Zero();
  18296. _this._worldMatrixDeterminant = 0;
  18297. _this._absolutePosition = BABYLON.Vector3.Zero();
  18298. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18299. _this._postMultiplyPivotMatrix = false;
  18300. _this._isWorldMatrixFrozen = false;
  18301. /**
  18302. * An event triggered after the world matrix is updated
  18303. */
  18304. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18305. _this._nonUniformScaling = false;
  18306. if (isPure) {
  18307. _this.getScene().addTransformNode(_this);
  18308. }
  18309. return _this;
  18310. }
  18311. /**
  18312. * Gets a string idenfifying the name of the class
  18313. * @returns "TransformNode" string
  18314. */
  18315. TransformNode.prototype.getClassName = function () {
  18316. return "TransformNode";
  18317. };
  18318. Object.defineProperty(TransformNode.prototype, "rotation", {
  18319. /**
  18320. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18321. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18322. * Default : (0.0, 0.0, 0.0)
  18323. */
  18324. get: function () {
  18325. return this._rotation;
  18326. },
  18327. set: function (newRotation) {
  18328. this._rotation = newRotation;
  18329. },
  18330. enumerable: true,
  18331. configurable: true
  18332. });
  18333. Object.defineProperty(TransformNode.prototype, "scaling", {
  18334. /**
  18335. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18336. * Default : (1.0, 1.0, 1.0)
  18337. */
  18338. get: function () {
  18339. return this._scaling;
  18340. },
  18341. /**
  18342. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18343. * Default : (1.0, 1.0, 1.0)
  18344. */
  18345. set: function (newScaling) {
  18346. this._scaling = newScaling;
  18347. },
  18348. enumerable: true,
  18349. configurable: true
  18350. });
  18351. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18352. /**
  18353. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18354. * It's null by default.
  18355. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18356. */
  18357. get: function () {
  18358. return this._rotationQuaternion;
  18359. },
  18360. set: function (quaternion) {
  18361. this._rotationQuaternion = quaternion;
  18362. //reset the rotation vector.
  18363. if (quaternion && this.rotation.length()) {
  18364. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18365. }
  18366. },
  18367. enumerable: true,
  18368. configurable: true
  18369. });
  18370. Object.defineProperty(TransformNode.prototype, "forward", {
  18371. /**
  18372. * The forward direction of that transform in world space.
  18373. */
  18374. get: function () {
  18375. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18376. },
  18377. enumerable: true,
  18378. configurable: true
  18379. });
  18380. Object.defineProperty(TransformNode.prototype, "up", {
  18381. /**
  18382. * The up direction of that transform in world space.
  18383. */
  18384. get: function () {
  18385. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18386. },
  18387. enumerable: true,
  18388. configurable: true
  18389. });
  18390. Object.defineProperty(TransformNode.prototype, "right", {
  18391. /**
  18392. * The right direction of that transform in world space.
  18393. */
  18394. get: function () {
  18395. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18396. },
  18397. enumerable: true,
  18398. configurable: true
  18399. });
  18400. /**
  18401. * Returns the latest update of the World matrix
  18402. * Returns a Matrix.
  18403. */
  18404. TransformNode.prototype.getWorldMatrix = function () {
  18405. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18406. this.computeWorldMatrix();
  18407. }
  18408. return this._worldMatrix;
  18409. };
  18410. /** @hidden */
  18411. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18412. return this._worldMatrixDeterminant;
  18413. };
  18414. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18415. /**
  18416. * Returns directly the latest state of the mesh World matrix.
  18417. * A Matrix is returned.
  18418. */
  18419. get: function () {
  18420. return this._worldMatrix;
  18421. },
  18422. enumerable: true,
  18423. configurable: true
  18424. });
  18425. /**
  18426. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18427. * Returns the TransformNode.
  18428. */
  18429. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18430. this._poseMatrix.copyFrom(matrix);
  18431. return this;
  18432. };
  18433. /**
  18434. * Returns the mesh Pose matrix.
  18435. * Returned object : Matrix
  18436. */
  18437. TransformNode.prototype.getPoseMatrix = function () {
  18438. return this._poseMatrix;
  18439. };
  18440. TransformNode.prototype._isSynchronized = function () {
  18441. if (this._isDirty) {
  18442. return false;
  18443. }
  18444. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18445. return false;
  18446. if (this._cache.pivotMatrixUpdated) {
  18447. return false;
  18448. }
  18449. if (this.infiniteDistance) {
  18450. return false;
  18451. }
  18452. if (!this._cache.position.equals(this.position))
  18453. return false;
  18454. if (this.rotationQuaternion) {
  18455. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18456. return false;
  18457. }
  18458. if (!this._cache.rotation.equals(this.rotation))
  18459. return false;
  18460. if (!this._cache.scaling.equals(this.scaling))
  18461. return false;
  18462. return true;
  18463. };
  18464. TransformNode.prototype._initCache = function () {
  18465. _super.prototype._initCache.call(this);
  18466. this._cache.localMatrixUpdated = false;
  18467. this._cache.position = BABYLON.Vector3.Zero();
  18468. this._cache.scaling = BABYLON.Vector3.Zero();
  18469. this._cache.rotation = BABYLON.Vector3.Zero();
  18470. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18471. this._cache.billboardMode = -1;
  18472. };
  18473. TransformNode.prototype.markAsDirty = function (property) {
  18474. if (property === "rotation") {
  18475. this.rotationQuaternion = null;
  18476. }
  18477. this._currentRenderId = Number.MAX_VALUE;
  18478. this._isDirty = true;
  18479. return this;
  18480. };
  18481. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18482. /**
  18483. * Returns the current mesh absolute position.
  18484. * Retuns a Vector3.
  18485. */
  18486. get: function () {
  18487. return this._absolutePosition;
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. /**
  18493. * Sets a new matrix to apply before all other transformation
  18494. * @param matrix defines the transform matrix
  18495. * @returns the current TransformNode
  18496. */
  18497. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18498. return this.setPivotMatrix(matrix, false);
  18499. };
  18500. /**
  18501. * Sets a new pivot matrix to the current node
  18502. * @param matrix defines the new pivot matrix to use
  18503. * @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
  18504. * @returns the current TransformNode
  18505. */
  18506. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18507. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18508. this._pivotMatrix = matrix.clone();
  18509. this._cache.pivotMatrixUpdated = true;
  18510. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18511. if (this._postMultiplyPivotMatrix) {
  18512. if (!this._pivotMatrixInverse) {
  18513. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18514. }
  18515. else {
  18516. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18517. }
  18518. }
  18519. return this;
  18520. };
  18521. /**
  18522. * Returns the mesh pivot matrix.
  18523. * Default : Identity.
  18524. * A Matrix is returned.
  18525. */
  18526. TransformNode.prototype.getPivotMatrix = function () {
  18527. return this._pivotMatrix;
  18528. };
  18529. /**
  18530. * Prevents the World matrix to be computed any longer.
  18531. * Returns the TransformNode.
  18532. */
  18533. TransformNode.prototype.freezeWorldMatrix = function () {
  18534. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18535. this.computeWorldMatrix(true);
  18536. this._isWorldMatrixFrozen = true;
  18537. return this;
  18538. };
  18539. /**
  18540. * Allows back the World matrix computation.
  18541. * Returns the TransformNode.
  18542. */
  18543. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18544. this._isWorldMatrixFrozen = false;
  18545. this.computeWorldMatrix(true);
  18546. return this;
  18547. };
  18548. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18549. /**
  18550. * True if the World matrix has been frozen.
  18551. * Returns a boolean.
  18552. */
  18553. get: function () {
  18554. return this._isWorldMatrixFrozen;
  18555. },
  18556. enumerable: true,
  18557. configurable: true
  18558. });
  18559. /**
  18560. * Retuns the mesh absolute position in the World.
  18561. * Returns a Vector3.
  18562. */
  18563. TransformNode.prototype.getAbsolutePosition = function () {
  18564. this.computeWorldMatrix();
  18565. return this._absolutePosition;
  18566. };
  18567. /**
  18568. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18569. * Returns the TransformNode.
  18570. */
  18571. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18572. if (!absolutePosition) {
  18573. return this;
  18574. }
  18575. var absolutePositionX;
  18576. var absolutePositionY;
  18577. var absolutePositionZ;
  18578. if (absolutePosition.x === undefined) {
  18579. if (arguments.length < 3) {
  18580. return this;
  18581. }
  18582. absolutePositionX = arguments[0];
  18583. absolutePositionY = arguments[1];
  18584. absolutePositionZ = arguments[2];
  18585. }
  18586. else {
  18587. absolutePositionX = absolutePosition.x;
  18588. absolutePositionY = absolutePosition.y;
  18589. absolutePositionZ = absolutePosition.z;
  18590. }
  18591. if (this.parent) {
  18592. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18593. invertParentWorldMatrix.invert();
  18594. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18595. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18596. }
  18597. else {
  18598. this.position.x = absolutePositionX;
  18599. this.position.y = absolutePositionY;
  18600. this.position.z = absolutePositionZ;
  18601. }
  18602. return this;
  18603. };
  18604. /**
  18605. * Sets the mesh position in its local space.
  18606. * Returns the TransformNode.
  18607. */
  18608. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18609. this.computeWorldMatrix();
  18610. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18611. return this;
  18612. };
  18613. /**
  18614. * Returns the mesh position in the local space from the current World matrix values.
  18615. * Returns a new Vector3.
  18616. */
  18617. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18618. this.computeWorldMatrix();
  18619. var invLocalWorldMatrix = this._localWorld.clone();
  18620. invLocalWorldMatrix.invert();
  18621. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18622. };
  18623. /**
  18624. * Translates the mesh along the passed Vector3 in its local space.
  18625. * Returns the TransformNode.
  18626. */
  18627. TransformNode.prototype.locallyTranslate = function (vector3) {
  18628. this.computeWorldMatrix(true);
  18629. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18630. return this;
  18631. };
  18632. /**
  18633. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18634. * @param targetPoint the position (must be in same space as current mesh) to look at
  18635. * @param yawCor optional yaw (y-axis) correction in radians
  18636. * @param pitchCor optional pitch (x-axis) correction in radians
  18637. * @param rollCor optional roll (z-axis) correction in radians
  18638. * @param space the choosen space of the target
  18639. * @returns the TransformNode.
  18640. */
  18641. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18642. if (yawCor === void 0) { yawCor = 0; }
  18643. if (pitchCor === void 0) { pitchCor = 0; }
  18644. if (rollCor === void 0) { rollCor = 0; }
  18645. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18646. var dv = TransformNode._lookAtVectorCache;
  18647. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18648. targetPoint.subtractToRef(pos, dv);
  18649. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18650. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18651. var pitch = Math.atan2(dv.y, len);
  18652. if (this.rotationQuaternion) {
  18653. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18654. }
  18655. else {
  18656. this.rotation.x = pitch + pitchCor;
  18657. this.rotation.y = yaw + yawCor;
  18658. this.rotation.z = rollCor;
  18659. }
  18660. return this;
  18661. };
  18662. /**
  18663. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18664. * This Vector3 is expressed in the World space.
  18665. */
  18666. TransformNode.prototype.getDirection = function (localAxis) {
  18667. var result = BABYLON.Vector3.Zero();
  18668. this.getDirectionToRef(localAxis, result);
  18669. return result;
  18670. };
  18671. /**
  18672. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18673. * localAxis is expressed in the mesh local space.
  18674. * result is computed in the Wordl space from the mesh World matrix.
  18675. * Returns the TransformNode.
  18676. */
  18677. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18678. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18679. return this;
  18680. };
  18681. /**
  18682. * Sets a new pivot point to the current node
  18683. * @param point defines the new pivot point to use
  18684. * @param space defines if the point is in world or local space (local by default)
  18685. * @returns the current TransformNode
  18686. */
  18687. TransformNode.prototype.setPivotPoint = function (point, space) {
  18688. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18689. if (this.getScene().getRenderId() == 0) {
  18690. this.computeWorldMatrix(true);
  18691. }
  18692. var wm = this.getWorldMatrix();
  18693. if (space == BABYLON.Space.WORLD) {
  18694. var tmat = BABYLON.Tmp.Matrix[0];
  18695. wm.invertToRef(tmat);
  18696. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18697. }
  18698. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18699. };
  18700. /**
  18701. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18702. */
  18703. TransformNode.prototype.getPivotPoint = function () {
  18704. var point = BABYLON.Vector3.Zero();
  18705. this.getPivotPointToRef(point);
  18706. return point;
  18707. };
  18708. /**
  18709. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18710. * Returns the TransformNode.
  18711. */
  18712. TransformNode.prototype.getPivotPointToRef = function (result) {
  18713. result.x = -this._pivotMatrix.m[12];
  18714. result.y = -this._pivotMatrix.m[13];
  18715. result.z = -this._pivotMatrix.m[14];
  18716. return this;
  18717. };
  18718. /**
  18719. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18720. */
  18721. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18722. var point = BABYLON.Vector3.Zero();
  18723. this.getAbsolutePivotPointToRef(point);
  18724. return point;
  18725. };
  18726. /**
  18727. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18728. * Returns the TransformNode.
  18729. */
  18730. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18731. result.x = this._pivotMatrix.m[12];
  18732. result.y = this._pivotMatrix.m[13];
  18733. result.z = this._pivotMatrix.m[14];
  18734. this.getPivotPointToRef(result);
  18735. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18736. return this;
  18737. };
  18738. /**
  18739. * Defines the passed node as the parent of the current node.
  18740. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18741. * Returns the TransformNode.
  18742. */
  18743. TransformNode.prototype.setParent = function (node) {
  18744. if (!node && !this.parent) {
  18745. return this;
  18746. }
  18747. if (!node) {
  18748. var rotation = BABYLON.Tmp.Quaternion[0];
  18749. var position = BABYLON.Tmp.Vector3[0];
  18750. var scale = BABYLON.Tmp.Vector3[1];
  18751. if (this.parent && this.parent.computeWorldMatrix) {
  18752. this.parent.computeWorldMatrix(true);
  18753. }
  18754. this.computeWorldMatrix(true);
  18755. this.getWorldMatrix().decompose(scale, rotation, position);
  18756. if (this.rotationQuaternion) {
  18757. this.rotationQuaternion.copyFrom(rotation);
  18758. }
  18759. else {
  18760. rotation.toEulerAnglesToRef(this.rotation);
  18761. }
  18762. this.scaling.x = scale.x;
  18763. this.scaling.y = scale.y;
  18764. this.scaling.z = scale.z;
  18765. this.position.x = position.x;
  18766. this.position.y = position.y;
  18767. this.position.z = position.z;
  18768. }
  18769. else {
  18770. var rotation = BABYLON.Tmp.Quaternion[0];
  18771. var position = BABYLON.Tmp.Vector3[0];
  18772. var scale = BABYLON.Tmp.Vector3[1];
  18773. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18774. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18775. this.computeWorldMatrix(true);
  18776. node.computeWorldMatrix(true);
  18777. node.getWorldMatrix().invertToRef(invParentMatrix);
  18778. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18779. diffMatrix.decompose(scale, rotation, position);
  18780. if (this.rotationQuaternion) {
  18781. this.rotationQuaternion.copyFrom(rotation);
  18782. }
  18783. else {
  18784. rotation.toEulerAnglesToRef(this.rotation);
  18785. }
  18786. this.position.x = position.x;
  18787. this.position.y = position.y;
  18788. this.position.z = position.z;
  18789. this.scaling.x = scale.x;
  18790. this.scaling.y = scale.y;
  18791. this.scaling.z = scale.z;
  18792. }
  18793. this.parent = node;
  18794. return this;
  18795. };
  18796. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18797. get: function () {
  18798. return this._nonUniformScaling;
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18804. if (this._nonUniformScaling === value) {
  18805. return false;
  18806. }
  18807. this._nonUniformScaling = value;
  18808. return true;
  18809. };
  18810. /**
  18811. * Attach the current TransformNode to another TransformNode associated with a bone
  18812. * @param bone Bone affecting the TransformNode
  18813. * @param affectedTransformNode TransformNode associated with the bone
  18814. */
  18815. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18816. this._transformToBoneReferal = affectedTransformNode;
  18817. this.parent = bone;
  18818. if (bone.getWorldMatrix().determinant() < 0) {
  18819. this.scalingDeterminant *= -1;
  18820. }
  18821. return this;
  18822. };
  18823. TransformNode.prototype.detachFromBone = function () {
  18824. if (!this.parent) {
  18825. return this;
  18826. }
  18827. if (this.parent.getWorldMatrix().determinant() < 0) {
  18828. this.scalingDeterminant *= -1;
  18829. }
  18830. this._transformToBoneReferal = null;
  18831. this.parent = null;
  18832. return this;
  18833. };
  18834. /**
  18835. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18836. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18837. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18838. * The passed axis is also normalized.
  18839. * Returns the TransformNode.
  18840. */
  18841. TransformNode.prototype.rotate = function (axis, amount, space) {
  18842. axis.normalize();
  18843. if (!this.rotationQuaternion) {
  18844. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18845. this.rotation = BABYLON.Vector3.Zero();
  18846. }
  18847. var rotationQuaternion;
  18848. if (!space || space === BABYLON.Space.LOCAL) {
  18849. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18850. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18851. }
  18852. else {
  18853. if (this.parent) {
  18854. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18855. invertParentWorldMatrix.invert();
  18856. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18857. }
  18858. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18859. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18860. }
  18861. return this;
  18862. };
  18863. /**
  18864. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18865. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18866. * The passed axis is also normalized.
  18867. * Returns the TransformNode.
  18868. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18869. */
  18870. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18871. axis.normalize();
  18872. if (!this.rotationQuaternion) {
  18873. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18874. this.rotation.copyFromFloats(0, 0, 0);
  18875. }
  18876. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18877. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18878. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18879. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18880. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18881. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18882. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18883. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18884. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18885. return this;
  18886. };
  18887. /**
  18888. * Translates the mesh along the axis vector for the passed distance in the given space.
  18889. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18890. * Returns the TransformNode.
  18891. */
  18892. TransformNode.prototype.translate = function (axis, distance, space) {
  18893. var displacementVector = axis.scale(distance);
  18894. if (!space || space === BABYLON.Space.LOCAL) {
  18895. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18896. this.setPositionWithLocalVector(tempV3);
  18897. }
  18898. else {
  18899. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18900. }
  18901. return this;
  18902. };
  18903. /**
  18904. * Adds a rotation step to the mesh current rotation.
  18905. * x, y, z are Euler angles expressed in radians.
  18906. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18907. * This means this rotation is made in the mesh local space only.
  18908. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18909. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18910. * ```javascript
  18911. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18912. * ```
  18913. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18914. * 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.
  18915. * Returns the TransformNode.
  18916. */
  18917. TransformNode.prototype.addRotation = function (x, y, z) {
  18918. var rotationQuaternion;
  18919. if (this.rotationQuaternion) {
  18920. rotationQuaternion = this.rotationQuaternion;
  18921. }
  18922. else {
  18923. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18924. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18925. }
  18926. var accumulation = BABYLON.Tmp.Quaternion[0];
  18927. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18928. rotationQuaternion.multiplyInPlace(accumulation);
  18929. if (!this.rotationQuaternion) {
  18930. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18931. }
  18932. return this;
  18933. };
  18934. /**
  18935. * Computes the mesh World matrix and returns it.
  18936. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18937. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18938. * If the parameter `force`is set to `true`, the actual computation is done.
  18939. * Returns the mesh World Matrix.
  18940. */
  18941. TransformNode.prototype.computeWorldMatrix = function (force) {
  18942. if (this._isWorldMatrixFrozen) {
  18943. return this._worldMatrix;
  18944. }
  18945. if (!force && this.isSynchronized(true)) {
  18946. this._currentRenderId = this.getScene().getRenderId();
  18947. return this._worldMatrix;
  18948. }
  18949. this._cache.position.copyFrom(this.position);
  18950. this._cache.scaling.copyFrom(this.scaling);
  18951. this._cache.pivotMatrixUpdated = false;
  18952. this._cache.billboardMode = this.billboardMode;
  18953. this._currentRenderId = this.getScene().getRenderId();
  18954. this._childRenderId = this.getScene().getRenderId();
  18955. this._isDirty = false;
  18956. // Scaling
  18957. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18958. // Rotation
  18959. //rotate, if quaternion is set and rotation was used
  18960. if (this.rotationQuaternion) {
  18961. var len = this.rotation.length();
  18962. if (len) {
  18963. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18964. this.rotation.copyFromFloats(0, 0, 0);
  18965. }
  18966. }
  18967. if (this.rotationQuaternion) {
  18968. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18969. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18970. }
  18971. else {
  18972. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18973. this._cache.rotation.copyFrom(this.rotation);
  18974. }
  18975. // Translation
  18976. var camera = this.getScene().activeCamera;
  18977. if (this.infiniteDistance && !this.parent && camera) {
  18978. var cameraWorldMatrix = camera.getWorldMatrix();
  18979. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18980. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18981. }
  18982. else {
  18983. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18984. }
  18985. // Composing transformations
  18986. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18987. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18988. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18989. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18990. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18991. // Need to decompose each rotation here
  18992. var currentPosition = BABYLON.Tmp.Vector3[3];
  18993. if (this.parent && this.parent.getWorldMatrix) {
  18994. if (this._transformToBoneReferal) {
  18995. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18996. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18997. }
  18998. else {
  18999. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19000. }
  19001. }
  19002. else {
  19003. currentPosition.copyFrom(this.position);
  19004. }
  19005. currentPosition.subtractInPlace(camera.globalPosition);
  19006. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19007. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19008. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19009. }
  19010. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19011. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19012. }
  19013. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19014. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19015. }
  19016. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19017. }
  19018. else {
  19019. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19020. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19021. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19022. }
  19023. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19024. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19025. }
  19026. // Post multiply inverse of pivotMatrix
  19027. if (this._postMultiplyPivotMatrix) {
  19028. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19029. }
  19030. // Local world
  19031. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19032. // Parent
  19033. if (this.parent && this.parent.getWorldMatrix) {
  19034. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19035. if (this._transformToBoneReferal) {
  19036. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19037. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19038. }
  19039. else {
  19040. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19041. }
  19042. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19043. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19044. this._worldMatrix.copyFrom(this._localWorld);
  19045. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19046. }
  19047. else {
  19048. if (this._transformToBoneReferal) {
  19049. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19050. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19051. }
  19052. else {
  19053. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19054. }
  19055. }
  19056. this._markSyncedWithParent();
  19057. }
  19058. else {
  19059. this._worldMatrix.copyFrom(this._localWorld);
  19060. }
  19061. // Normal matrix
  19062. if (!this.ignoreNonUniformScaling) {
  19063. if (this.scaling.isNonUniform) {
  19064. this._updateNonUniformScalingState(true);
  19065. }
  19066. else if (this.parent && this.parent._nonUniformScaling) {
  19067. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19068. }
  19069. else {
  19070. this._updateNonUniformScalingState(false);
  19071. }
  19072. }
  19073. else {
  19074. this._updateNonUniformScalingState(false);
  19075. }
  19076. this._afterComputeWorldMatrix();
  19077. // Absolute position
  19078. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19079. // Callbacks
  19080. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19081. if (!this._poseMatrix) {
  19082. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19083. }
  19084. // Cache the determinant
  19085. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19086. return this._worldMatrix;
  19087. };
  19088. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19089. };
  19090. /**
  19091. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19092. * @param func: callback function to add
  19093. *
  19094. * Returns the TransformNode.
  19095. */
  19096. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19097. this.onAfterWorldMatrixUpdateObservable.add(func);
  19098. return this;
  19099. };
  19100. /**
  19101. * Removes a registered callback function.
  19102. * Returns the TransformNode.
  19103. */
  19104. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19105. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19106. return this;
  19107. };
  19108. /**
  19109. * Clone the current transform node
  19110. * Returns the new transform node
  19111. * @param name Name of the new clone
  19112. * @param newParent New parent for the clone
  19113. * @param doNotCloneChildren Do not clone children hierarchy
  19114. */
  19115. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19116. var _this = this;
  19117. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19118. result.name = name;
  19119. result.id = name;
  19120. if (newParent) {
  19121. result.parent = newParent;
  19122. }
  19123. if (!doNotCloneChildren) {
  19124. // Children
  19125. var directDescendants = this.getDescendants(true);
  19126. for (var index = 0; index < directDescendants.length; index++) {
  19127. var child = directDescendants[index];
  19128. if (child.clone) {
  19129. child.clone(name + "." + child.name, result);
  19130. }
  19131. }
  19132. }
  19133. return result;
  19134. };
  19135. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19136. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19137. serializationObject.type = this.getClassName();
  19138. // Parent
  19139. if (this.parent) {
  19140. serializationObject.parentId = this.parent.id;
  19141. }
  19142. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19143. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19144. }
  19145. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19146. serializationObject.isEnabled = this.isEnabled();
  19147. // Parent
  19148. if (this.parent) {
  19149. serializationObject.parentId = this.parent.id;
  19150. }
  19151. return serializationObject;
  19152. };
  19153. // Statics
  19154. /**
  19155. * Returns a new TransformNode object parsed from the source provided.
  19156. * The parameter `parsedMesh` is the source.
  19157. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19158. */
  19159. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19160. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19161. if (BABYLON.Tags) {
  19162. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19163. }
  19164. if (parsedTransformNode.localMatrix) {
  19165. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19166. }
  19167. else if (parsedTransformNode.pivotMatrix) {
  19168. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19169. }
  19170. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19171. // Parent
  19172. if (parsedTransformNode.parentId) {
  19173. transformNode._waitingParentId = parsedTransformNode.parentId;
  19174. }
  19175. return transformNode;
  19176. };
  19177. /**
  19178. * Releases resources associated with this transform node.
  19179. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19180. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19181. */
  19182. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19183. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19184. // Animations
  19185. this.getScene().stopAnimation(this);
  19186. // Remove from scene
  19187. this.getScene().removeTransformNode(this);
  19188. this.onAfterWorldMatrixUpdateObservable.clear();
  19189. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19190. };
  19191. // Statics
  19192. TransformNode.BILLBOARDMODE_NONE = 0;
  19193. TransformNode.BILLBOARDMODE_X = 1;
  19194. TransformNode.BILLBOARDMODE_Y = 2;
  19195. TransformNode.BILLBOARDMODE_Z = 4;
  19196. TransformNode.BILLBOARDMODE_ALL = 7;
  19197. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19198. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19199. __decorate([
  19200. BABYLON.serializeAsVector3()
  19201. ], TransformNode.prototype, "_rotation", void 0);
  19202. __decorate([
  19203. BABYLON.serializeAsQuaternion()
  19204. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19205. __decorate([
  19206. BABYLON.serializeAsVector3()
  19207. ], TransformNode.prototype, "_scaling", void 0);
  19208. __decorate([
  19209. BABYLON.serialize()
  19210. ], TransformNode.prototype, "billboardMode", void 0);
  19211. __decorate([
  19212. BABYLON.serialize()
  19213. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19214. __decorate([
  19215. BABYLON.serialize()
  19216. ], TransformNode.prototype, "infiniteDistance", void 0);
  19217. __decorate([
  19218. BABYLON.serialize()
  19219. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19220. __decorate([
  19221. BABYLON.serializeAsVector3()
  19222. ], TransformNode.prototype, "position", void 0);
  19223. return TransformNode;
  19224. }(BABYLON.Node));
  19225. BABYLON.TransformNode = TransformNode;
  19226. })(BABYLON || (BABYLON = {}));
  19227. //# sourceMappingURL=babylon.transformNode.js.map
  19228. var BABYLON;
  19229. (function (BABYLON) {
  19230. /**
  19231. * Class used to store all common mesh properties
  19232. */
  19233. var AbstractMesh = /** @class */ (function (_super) {
  19234. __extends(AbstractMesh, _super);
  19235. // Constructor
  19236. /**
  19237. * Creates a new AbstractMesh
  19238. * @param name defines the name of the mesh
  19239. * @param scene defines the hosting scene
  19240. */
  19241. function AbstractMesh(name, scene) {
  19242. if (scene === void 0) { scene = null; }
  19243. var _this = _super.call(this, name, scene, false) || this;
  19244. _this._facetNb = 0; // facet number
  19245. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19246. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19247. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19248. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19249. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19250. _this._subDiv = {
  19251. max: 1,
  19252. X: 1,
  19253. Y: 1,
  19254. Z: 1
  19255. };
  19256. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19257. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19258. // Events
  19259. /**
  19260. * An event triggered when this mesh collides with another one
  19261. */
  19262. _this.onCollideObservable = new BABYLON.Observable();
  19263. /**
  19264. * An event triggered when the collision's position changes
  19265. */
  19266. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19267. /**
  19268. * An event triggered when material is changed
  19269. */
  19270. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19271. // Properties
  19272. /**
  19273. * Gets or sets the orientation for POV movement & rotation
  19274. */
  19275. _this.definedFacingForward = true;
  19276. /**
  19277. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19278. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19279. * * 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.
  19280. * @see http://doc.babylonjs.com/features/occlusionquery
  19281. */
  19282. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19283. /**
  19284. * 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:
  19285. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19286. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19287. * * 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.
  19288. * @see http://doc.babylonjs.com/features/occlusionquery
  19289. */
  19290. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19291. /**
  19292. * 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.
  19293. * The default value is -1 which means don't break the query and wait till the result
  19294. * @see http://doc.babylonjs.com/features/occlusionquery
  19295. */
  19296. _this.occlusionRetryCount = -1;
  19297. /** @hidden */
  19298. _this._occlusionInternalRetryCounter = 0;
  19299. /** @hidden */
  19300. _this._isOccluded = false;
  19301. /** @hidden */
  19302. _this._isOcclusionQueryInProgress = false;
  19303. _this._visibility = 1.0;
  19304. /** Gets or sets the alpha index used to sort transparent meshes
  19305. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19306. */
  19307. _this.alphaIndex = Number.MAX_VALUE;
  19308. /**
  19309. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19310. */
  19311. _this.isVisible = true;
  19312. /**
  19313. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19314. */
  19315. _this.isPickable = true;
  19316. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19317. _this.showSubMeshesBoundingBox = false;
  19318. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19319. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19320. */
  19321. _this.isBlocker = false;
  19322. /**
  19323. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19324. */
  19325. _this.enablePointerMoveEvents = false;
  19326. /**
  19327. * Specifies the rendering group id for this mesh (0 by default)
  19328. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19329. */
  19330. _this.renderingGroupId = 0;
  19331. _this._receiveShadows = false;
  19332. /**
  19333. * Gets or sets a boolean indicating if the outline must be rendered as well
  19334. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19335. */
  19336. _this.renderOutline = false;
  19337. /** Defines color to use when rendering outline */
  19338. _this.outlineColor = BABYLON.Color3.Red();
  19339. /** Define width to use when rendering outline */
  19340. _this.outlineWidth = 0.02;
  19341. /**
  19342. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19343. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19344. */
  19345. _this.renderOverlay = false;
  19346. /** Defines color to use when rendering overlay */
  19347. _this.overlayColor = BABYLON.Color3.Red();
  19348. /** Defines alpha to use when rendering overlay */
  19349. _this.overlayAlpha = 0.5;
  19350. _this._hasVertexAlpha = false;
  19351. _this._useVertexColors = true;
  19352. _this._computeBonesUsingShaders = true;
  19353. _this._numBoneInfluencers = 4;
  19354. _this._applyFog = true;
  19355. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19356. _this.useOctreeForRenderingSelection = true;
  19357. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19358. _this.useOctreeForPicking = true;
  19359. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19360. _this.useOctreeForCollisions = true;
  19361. _this._layerMask = 0x0FFFFFFF;
  19362. /**
  19363. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19364. */
  19365. _this.alwaysSelectAsActiveMesh = false;
  19366. /**
  19367. * Gets or sets the current action manager
  19368. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19369. */
  19370. _this.actionManager = null;
  19371. /**
  19372. * Gets or sets impostor used for physic simulation
  19373. * @see http://doc.babylonjs.com/features/physics_engine
  19374. */
  19375. _this.physicsImpostor = null;
  19376. // Collisions
  19377. _this._checkCollisions = false;
  19378. _this._collisionMask = -1;
  19379. _this._collisionGroup = -1;
  19380. /**
  19381. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19382. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19383. */
  19384. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19385. /**
  19386. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19387. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19388. */
  19389. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19390. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19391. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19392. // Edges
  19393. /**
  19394. * Defines edge width used when edgesRenderer is enabled
  19395. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19396. */
  19397. _this.edgesWidth = 1;
  19398. /**
  19399. * Defines edge color used when edgesRenderer is enabled
  19400. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19401. */
  19402. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19403. // Cache
  19404. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19405. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19406. /** @hidden */
  19407. _this._renderId = 0;
  19408. /** @hidden */
  19409. _this._intersectionsInProgress = new Array();
  19410. /** @hidden */
  19411. _this._unIndexed = false;
  19412. /** @hidden */
  19413. _this._lightSources = new Array();
  19414. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19415. if (collidedMesh === void 0) { collidedMesh = null; }
  19416. //TODO move this to the collision coordinator!
  19417. if (_this.getScene().workerCollisions)
  19418. newPosition.multiplyInPlace(_this._collider._radius);
  19419. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19420. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19421. _this.position.addInPlace(_this._diffPositionForCollisions);
  19422. }
  19423. if (collidedMesh) {
  19424. _this.onCollideObservable.notifyObservers(collidedMesh);
  19425. }
  19426. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19427. };
  19428. _this.getScene().addMesh(_this);
  19429. _this._resyncLightSources();
  19430. return _this;
  19431. }
  19432. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19433. /**
  19434. * No billboard
  19435. */
  19436. get: function () {
  19437. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19438. },
  19439. enumerable: true,
  19440. configurable: true
  19441. });
  19442. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19443. /** Billboard on X axis */
  19444. get: function () {
  19445. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19446. },
  19447. enumerable: true,
  19448. configurable: true
  19449. });
  19450. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19451. /** Billboard on Y axis */
  19452. get: function () {
  19453. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19454. },
  19455. enumerable: true,
  19456. configurable: true
  19457. });
  19458. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19459. /** Billboard on Z axis */
  19460. get: function () {
  19461. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19467. /** Billboard on all axes */
  19468. get: function () {
  19469. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19470. },
  19471. enumerable: true,
  19472. configurable: true
  19473. });
  19474. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19475. /**
  19476. * Gets the number of facets in the mesh
  19477. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19478. */
  19479. get: function () {
  19480. return this._facetNb;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19486. /**
  19487. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19488. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19489. */
  19490. get: function () {
  19491. return this._partitioningSubdivisions;
  19492. },
  19493. set: function (nb) {
  19494. this._partitioningSubdivisions = nb;
  19495. },
  19496. enumerable: true,
  19497. configurable: true
  19498. });
  19499. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19500. /**
  19501. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19502. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19503. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19504. */
  19505. get: function () {
  19506. return this._partitioningBBoxRatio;
  19507. },
  19508. set: function (ratio) {
  19509. this._partitioningBBoxRatio = ratio;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19515. /**
  19516. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19517. * Works only for updatable meshes.
  19518. * Doesn't work with multi-materials
  19519. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19520. */
  19521. get: function () {
  19522. return this._facetDepthSort;
  19523. },
  19524. set: function (sort) {
  19525. this._facetDepthSort = sort;
  19526. },
  19527. enumerable: true,
  19528. configurable: true
  19529. });
  19530. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19531. /**
  19532. * The location (Vector3) where the facet depth sort must be computed from.
  19533. * By default, the active camera position.
  19534. * Used only when facet depth sort is enabled
  19535. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19536. */
  19537. get: function () {
  19538. return this._facetDepthSortFrom;
  19539. },
  19540. set: function (location) {
  19541. this._facetDepthSortFrom = location;
  19542. },
  19543. enumerable: true,
  19544. configurable: true
  19545. });
  19546. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19547. /**
  19548. * gets a boolean indicating if facetData is enabled
  19549. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19550. */
  19551. get: function () {
  19552. return this._facetDataEnabled;
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. /** @hidden */
  19558. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19559. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19560. return false;
  19561. }
  19562. this._markSubMeshesAsMiscDirty();
  19563. return true;
  19564. };
  19565. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19566. /** Set a function to call when this mesh collides with another one */
  19567. set: function (callback) {
  19568. if (this._onCollideObserver) {
  19569. this.onCollideObservable.remove(this._onCollideObserver);
  19570. }
  19571. this._onCollideObserver = this.onCollideObservable.add(callback);
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19577. /** Set a function to call when the collision's position changes */
  19578. set: function (callback) {
  19579. if (this._onCollisionPositionChangeObserver) {
  19580. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19581. }
  19582. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19583. },
  19584. enumerable: true,
  19585. configurable: true
  19586. });
  19587. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19588. /**
  19589. * 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
  19590. * @see http://doc.babylonjs.com/features/occlusionquery
  19591. */
  19592. get: function () {
  19593. return this._isOccluded;
  19594. },
  19595. set: function (value) {
  19596. this._isOccluded = value;
  19597. },
  19598. enumerable: true,
  19599. configurable: true
  19600. });
  19601. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19602. /**
  19603. * Flag to check the progress status of the query
  19604. * @see http://doc.babylonjs.com/features/occlusionquery
  19605. */
  19606. get: function () {
  19607. return this._isOcclusionQueryInProgress;
  19608. },
  19609. enumerable: true,
  19610. configurable: true
  19611. });
  19612. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19613. /**
  19614. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19615. */
  19616. get: function () {
  19617. return this._visibility;
  19618. },
  19619. /**
  19620. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19621. */
  19622. set: function (value) {
  19623. if (this._visibility === value) {
  19624. return;
  19625. }
  19626. this._visibility = value;
  19627. this._markSubMeshesAsMiscDirty();
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Object.defineProperty(AbstractMesh.prototype, "material", {
  19633. /** Gets or sets current material */
  19634. get: function () {
  19635. return this._material;
  19636. },
  19637. set: function (value) {
  19638. if (this._material === value) {
  19639. return;
  19640. }
  19641. this._material = value;
  19642. if (this.onMaterialChangedObservable.hasObservers) {
  19643. this.onMaterialChangedObservable.notifyObservers(this);
  19644. }
  19645. if (!this.subMeshes) {
  19646. return;
  19647. }
  19648. this._unBindEffect();
  19649. },
  19650. enumerable: true,
  19651. configurable: true
  19652. });
  19653. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19654. /**
  19655. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19656. * @see http://doc.babylonjs.com/babylon101/shadows
  19657. */
  19658. get: function () {
  19659. return this._receiveShadows;
  19660. },
  19661. set: function (value) {
  19662. if (this._receiveShadows === value) {
  19663. return;
  19664. }
  19665. this._receiveShadows = value;
  19666. this._markSubMeshesAsLightDirty();
  19667. },
  19668. enumerable: true,
  19669. configurable: true
  19670. });
  19671. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19672. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19673. get: function () {
  19674. return this._hasVertexAlpha;
  19675. },
  19676. set: function (value) {
  19677. if (this._hasVertexAlpha === value) {
  19678. return;
  19679. }
  19680. this._hasVertexAlpha = value;
  19681. this._markSubMeshesAsAttributesDirty();
  19682. this._markSubMeshesAsMiscDirty();
  19683. },
  19684. enumerable: true,
  19685. configurable: true
  19686. });
  19687. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19688. /** 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) */
  19689. get: function () {
  19690. return this._useVertexColors;
  19691. },
  19692. set: function (value) {
  19693. if (this._useVertexColors === value) {
  19694. return;
  19695. }
  19696. this._useVertexColors = value;
  19697. this._markSubMeshesAsAttributesDirty();
  19698. },
  19699. enumerable: true,
  19700. configurable: true
  19701. });
  19702. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19703. /**
  19704. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19705. */
  19706. get: function () {
  19707. return this._computeBonesUsingShaders;
  19708. },
  19709. set: function (value) {
  19710. if (this._computeBonesUsingShaders === value) {
  19711. return;
  19712. }
  19713. this._computeBonesUsingShaders = value;
  19714. this._markSubMeshesAsAttributesDirty();
  19715. },
  19716. enumerable: true,
  19717. configurable: true
  19718. });
  19719. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19720. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19721. get: function () {
  19722. return this._numBoneInfluencers;
  19723. },
  19724. set: function (value) {
  19725. if (this._numBoneInfluencers === value) {
  19726. return;
  19727. }
  19728. this._numBoneInfluencers = value;
  19729. this._markSubMeshesAsAttributesDirty();
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19735. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19736. get: function () {
  19737. return this._applyFog;
  19738. },
  19739. set: function (value) {
  19740. if (this._applyFog === value) {
  19741. return;
  19742. }
  19743. this._applyFog = value;
  19744. this._markSubMeshesAsMiscDirty();
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19750. /**
  19751. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19752. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19753. */
  19754. get: function () {
  19755. return this._layerMask;
  19756. },
  19757. set: function (value) {
  19758. if (value === this._layerMask) {
  19759. return;
  19760. }
  19761. this._layerMask = value;
  19762. this._resyncLightSources();
  19763. },
  19764. enumerable: true,
  19765. configurable: true
  19766. });
  19767. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19768. /**
  19769. * Gets or sets a collision mask used to mask collisions (default is -1).
  19770. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19771. */
  19772. get: function () {
  19773. return this._collisionMask;
  19774. },
  19775. set: function (mask) {
  19776. this._collisionMask = !isNaN(mask) ? mask : -1;
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19782. /**
  19783. * Gets or sets the current collision group mask (-1 by default).
  19784. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19785. */
  19786. get: function () {
  19787. return this._collisionGroup;
  19788. },
  19789. set: function (mask) {
  19790. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19796. /** @hidden */
  19797. get: function () {
  19798. return null;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19804. get: function () {
  19805. return this._skeleton;
  19806. },
  19807. /**
  19808. * Gets or sets a skeleton to apply skining transformations
  19809. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19810. */
  19811. set: function (value) {
  19812. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19813. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19814. }
  19815. if (value && value.needInitialSkinMatrix) {
  19816. value._registerMeshWithPoseMatrix(this);
  19817. }
  19818. this._skeleton = value;
  19819. if (!this._skeleton) {
  19820. this._bonesTransformMatrices = null;
  19821. }
  19822. this._markSubMeshesAsAttributesDirty();
  19823. },
  19824. enumerable: true,
  19825. configurable: true
  19826. });
  19827. /**
  19828. * Returns the string "AbstractMesh"
  19829. * @returns "AbstractMesh"
  19830. */
  19831. AbstractMesh.prototype.getClassName = function () {
  19832. return "AbstractMesh";
  19833. };
  19834. /**
  19835. * Gets a string representation of the current mesh
  19836. * @param fullDetails defines a boolean indicating if full details must be included
  19837. * @returns a string representation of the current mesh
  19838. */
  19839. AbstractMesh.prototype.toString = function (fullDetails) {
  19840. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19841. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19842. if (this._skeleton) {
  19843. ret += ", skeleton: " + this._skeleton.name;
  19844. }
  19845. if (fullDetails) {
  19846. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19847. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19848. }
  19849. return ret;
  19850. };
  19851. /** @hidden */
  19852. AbstractMesh.prototype._rebuild = function () {
  19853. if (this._occlusionQuery) {
  19854. this._occlusionQuery = null;
  19855. }
  19856. if (this._edgesRenderer) {
  19857. this._edgesRenderer._rebuild();
  19858. }
  19859. if (!this.subMeshes) {
  19860. return;
  19861. }
  19862. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19863. var subMesh = _a[_i];
  19864. subMesh._rebuild();
  19865. }
  19866. };
  19867. /** @hidden */
  19868. AbstractMesh.prototype._resyncLightSources = function () {
  19869. this._lightSources.length = 0;
  19870. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19871. var light = _a[_i];
  19872. if (!light.isEnabled()) {
  19873. continue;
  19874. }
  19875. if (light.canAffectMesh(this)) {
  19876. this._lightSources.push(light);
  19877. }
  19878. }
  19879. this._markSubMeshesAsLightDirty();
  19880. };
  19881. /** @hidden */
  19882. AbstractMesh.prototype._resyncLighSource = function (light) {
  19883. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19884. var index = this._lightSources.indexOf(light);
  19885. if (index === -1) {
  19886. if (!isIn) {
  19887. return;
  19888. }
  19889. this._lightSources.push(light);
  19890. }
  19891. else {
  19892. if (isIn) {
  19893. return;
  19894. }
  19895. this._lightSources.splice(index, 1);
  19896. }
  19897. this._markSubMeshesAsLightDirty();
  19898. };
  19899. /** @hidden */
  19900. AbstractMesh.prototype._unBindEffect = function () {
  19901. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19902. var subMesh = _a[_i];
  19903. subMesh.setEffect(null);
  19904. }
  19905. };
  19906. /** @hidden */
  19907. AbstractMesh.prototype._removeLightSource = function (light) {
  19908. var index = this._lightSources.indexOf(light);
  19909. if (index === -1) {
  19910. return;
  19911. }
  19912. this._lightSources.splice(index, 1);
  19913. this._markSubMeshesAsLightDirty();
  19914. };
  19915. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19916. if (!this.subMeshes) {
  19917. return;
  19918. }
  19919. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19920. var subMesh = _a[_i];
  19921. if (subMesh._materialDefines) {
  19922. func(subMesh._materialDefines);
  19923. }
  19924. }
  19925. };
  19926. /** @hidden */
  19927. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19928. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19929. };
  19930. /** @hidden */
  19931. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19932. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19933. };
  19934. /** @hidden */
  19935. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19936. if (!this.subMeshes) {
  19937. return;
  19938. }
  19939. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19940. var subMesh = _a[_i];
  19941. var material = subMesh.getMaterial();
  19942. if (material) {
  19943. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19944. }
  19945. }
  19946. };
  19947. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19948. /**
  19949. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19950. */
  19951. get: function () {
  19952. return this._scaling;
  19953. },
  19954. set: function (newScaling) {
  19955. this._scaling = newScaling;
  19956. if (this.physicsImpostor) {
  19957. this.physicsImpostor.forceUpdate();
  19958. }
  19959. },
  19960. enumerable: true,
  19961. configurable: true
  19962. });
  19963. // Methods
  19964. /**
  19965. * Disables the mesh edge rendering mode
  19966. * @returns the currentAbstractMesh
  19967. */
  19968. AbstractMesh.prototype.disableEdgesRendering = function () {
  19969. if (this._edgesRenderer) {
  19970. this._edgesRenderer.dispose();
  19971. this._edgesRenderer = null;
  19972. }
  19973. return this;
  19974. };
  19975. /**
  19976. * Enables the edge rendering mode on the mesh.
  19977. * This mode makes the mesh edges visible
  19978. * @param epsilon defines the maximal distance between two angles to detect a face
  19979. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19980. * @returns the currentAbstractMesh
  19981. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19982. */
  19983. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19984. if (epsilon === void 0) { epsilon = 0.95; }
  19985. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19986. this.disableEdgesRendering();
  19987. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19988. return this;
  19989. };
  19990. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  19991. /**
  19992. * Gets the edgesRenderer associated with the mesh
  19993. */
  19994. get: function () {
  19995. return this._edgesRenderer;
  19996. },
  19997. enumerable: true,
  19998. configurable: true
  19999. });
  20000. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20001. /**
  20002. * Returns true if the mesh is blocked. Implemented by child classes
  20003. */
  20004. get: function () {
  20005. return false;
  20006. },
  20007. enumerable: true,
  20008. configurable: true
  20009. });
  20010. /**
  20011. * Returns the mesh itself by default. Implemented by child classes
  20012. * @param camera defines the camera to use to pick the right LOD level
  20013. * @returns the currentAbstractMesh
  20014. */
  20015. AbstractMesh.prototype.getLOD = function (camera) {
  20016. return this;
  20017. };
  20018. /**
  20019. * Returns 0 by default. Implemented by child classes
  20020. * @returns an integer
  20021. */
  20022. AbstractMesh.prototype.getTotalVertices = function () {
  20023. return 0;
  20024. };
  20025. /**
  20026. * Returns null by default. Implemented by child classes
  20027. * @returns null
  20028. */
  20029. AbstractMesh.prototype.getIndices = function () {
  20030. return null;
  20031. };
  20032. /**
  20033. * Returns the array of the requested vertex data kind. Implemented by child classes
  20034. * @param kind defines the vertex data kind to use
  20035. * @returns null
  20036. */
  20037. AbstractMesh.prototype.getVerticesData = function (kind) {
  20038. return null;
  20039. };
  20040. /**
  20041. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20042. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20043. * Note that a new underlying VertexBuffer object is created each call.
  20044. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20045. * @param kind defines vertex data kind:
  20046. * * BABYLON.VertexBuffer.PositionKind
  20047. * * BABYLON.VertexBuffer.UVKind
  20048. * * BABYLON.VertexBuffer.UV2Kind
  20049. * * BABYLON.VertexBuffer.UV3Kind
  20050. * * BABYLON.VertexBuffer.UV4Kind
  20051. * * BABYLON.VertexBuffer.UV5Kind
  20052. * * BABYLON.VertexBuffer.UV6Kind
  20053. * * BABYLON.VertexBuffer.ColorKind
  20054. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20055. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20056. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20057. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20058. * @param data defines the data source
  20059. * @param updatable defines if the data must be flagged as updatable (or static)
  20060. * @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
  20061. * @returns the current mesh
  20062. */
  20063. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20064. return this;
  20065. };
  20066. /**
  20067. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20068. * If the mesh has no geometry, it is simply returned as it is.
  20069. * @param kind defines vertex data kind:
  20070. * * BABYLON.VertexBuffer.PositionKind
  20071. * * BABYLON.VertexBuffer.UVKind
  20072. * * BABYLON.VertexBuffer.UV2Kind
  20073. * * BABYLON.VertexBuffer.UV3Kind
  20074. * * BABYLON.VertexBuffer.UV4Kind
  20075. * * BABYLON.VertexBuffer.UV5Kind
  20076. * * BABYLON.VertexBuffer.UV6Kind
  20077. * * BABYLON.VertexBuffer.ColorKind
  20078. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20079. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20080. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20081. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20082. * @param data defines the data source
  20083. * @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
  20084. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20085. * @returns the current mesh
  20086. */
  20087. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20088. return this;
  20089. };
  20090. /**
  20091. * Sets the mesh indices,
  20092. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20093. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20094. * @param totalVertices Defines the total number of vertices
  20095. * @returns the current mesh
  20096. */
  20097. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20098. return this;
  20099. };
  20100. /**
  20101. * Gets a boolean indicating if specific vertex data is present
  20102. * @param kind defines the vertex data kind to use
  20103. * @returns true is data kind is present
  20104. */
  20105. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20106. return false;
  20107. };
  20108. /**
  20109. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20110. * @returns a BoundingInfo
  20111. */
  20112. AbstractMesh.prototype.getBoundingInfo = function () {
  20113. if (this._masterMesh) {
  20114. return this._masterMesh.getBoundingInfo();
  20115. }
  20116. if (!this._boundingInfo) {
  20117. // this._boundingInfo is being created here
  20118. this._updateBoundingInfo();
  20119. }
  20120. // cannot be null.
  20121. return this._boundingInfo;
  20122. };
  20123. /**
  20124. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20125. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20126. * @returns the current mesh
  20127. */
  20128. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20129. if (includeDescendants === void 0) { includeDescendants = true; }
  20130. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20131. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20132. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20133. if (maxDimension === 0) {
  20134. return this;
  20135. }
  20136. var scale = 1 / maxDimension;
  20137. this.scaling.scaleInPlace(scale);
  20138. return this;
  20139. };
  20140. /**
  20141. * Overwrite the current bounding info
  20142. * @param boundingInfo defines the new bounding info
  20143. * @returns the current mesh
  20144. */
  20145. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20146. this._boundingInfo = boundingInfo;
  20147. return this;
  20148. };
  20149. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20150. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20151. get: function () {
  20152. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. /** @hidden */
  20158. AbstractMesh.prototype._preActivate = function () {
  20159. };
  20160. /** @hidden */
  20161. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20162. };
  20163. /** @hidden */
  20164. AbstractMesh.prototype._activate = function (renderId) {
  20165. this._renderId = renderId;
  20166. };
  20167. /**
  20168. * Gets the current world matrix
  20169. * @returns a Matrix
  20170. */
  20171. AbstractMesh.prototype.getWorldMatrix = function () {
  20172. if (this._masterMesh) {
  20173. return this._masterMesh.getWorldMatrix();
  20174. }
  20175. return _super.prototype.getWorldMatrix.call(this);
  20176. };
  20177. /** @hidden */
  20178. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20179. if (this._masterMesh) {
  20180. return this._masterMesh._getWorldMatrixDeterminant();
  20181. }
  20182. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20183. };
  20184. // ================================== Point of View Movement =================================
  20185. /**
  20186. * Perform relative position change from the point of view of behind the front of the mesh.
  20187. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20188. * Supports definition of mesh facing forward or backward
  20189. * @param amountRight defines the distance on the right axis
  20190. * @param amountUp defines the distance on the up axis
  20191. * @param amountForward defines the distance on the forward axis
  20192. * @returns the current mesh
  20193. */
  20194. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20195. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20196. return this;
  20197. };
  20198. /**
  20199. * Calculate relative position change from the point of view of behind the front of the mesh.
  20200. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20201. * Supports definition of mesh facing forward or backward
  20202. * @param amountRight defines the distance on the right axis
  20203. * @param amountUp defines the distance on the up axis
  20204. * @param amountForward defines the distance on the forward axis
  20205. * @returns the new displacement vector
  20206. */
  20207. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20208. var rotMatrix = new BABYLON.Matrix();
  20209. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20210. rotQuaternion.toRotationMatrix(rotMatrix);
  20211. var translationDelta = BABYLON.Vector3.Zero();
  20212. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20213. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20214. return translationDelta;
  20215. };
  20216. // ================================== Point of View Rotation =================================
  20217. /**
  20218. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20219. * Supports definition of mesh facing forward or backward
  20220. * @param flipBack defines the flip
  20221. * @param twirlClockwise defines the twirl
  20222. * @param tiltRight defines the tilt
  20223. * @returns the current mesh
  20224. */
  20225. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20226. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20227. return this;
  20228. };
  20229. /**
  20230. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20231. * Supports definition of mesh facing forward or backward.
  20232. * @param flipBack defines the flip
  20233. * @param twirlClockwise defines the twirl
  20234. * @param tiltRight defines the tilt
  20235. * @returns the new rotation vector
  20236. */
  20237. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20238. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20239. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20240. };
  20241. /**
  20242. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20243. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20244. * @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
  20245. * @returns the new bounding vectors
  20246. */
  20247. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20248. if (includeDescendants === void 0) { includeDescendants = true; }
  20249. if (predicate === void 0) { predicate = null; }
  20250. // Ensures that all world matrix will be recomputed.
  20251. this.getScene().incrementRenderId();
  20252. this.computeWorldMatrix(true);
  20253. var min;
  20254. var max;
  20255. var boundingInfo = this.getBoundingInfo();
  20256. if (!this.subMeshes) {
  20257. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20258. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20259. }
  20260. else {
  20261. min = boundingInfo.boundingBox.minimumWorld;
  20262. max = boundingInfo.boundingBox.maximumWorld;
  20263. }
  20264. if (includeDescendants) {
  20265. var descendants = this.getDescendants(false);
  20266. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20267. var descendant = descendants_1[_i];
  20268. var childMesh = descendant;
  20269. childMesh.computeWorldMatrix(true);
  20270. // Filters meshes based on custom predicate function.
  20271. if (predicate && !predicate(childMesh)) {
  20272. continue;
  20273. }
  20274. //make sure we have the needed params to get mix and max
  20275. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20276. continue;
  20277. }
  20278. var childBoundingInfo = childMesh.getBoundingInfo();
  20279. var boundingBox = childBoundingInfo.boundingBox;
  20280. var minBox = boundingBox.minimumWorld;
  20281. var maxBox = boundingBox.maximumWorld;
  20282. BABYLON.Tools.CheckExtends(minBox, min, max);
  20283. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20284. }
  20285. }
  20286. return {
  20287. min: min,
  20288. max: max
  20289. };
  20290. };
  20291. /** @hidden */
  20292. AbstractMesh.prototype._updateBoundingInfo = function () {
  20293. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20294. this._boundingInfo.update(this.worldMatrixFromCache);
  20295. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20296. return this;
  20297. };
  20298. /** @hidden */
  20299. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20300. if (!this.subMeshes) {
  20301. return this;
  20302. }
  20303. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20304. var subMesh = this.subMeshes[subIndex];
  20305. if (!subMesh.IsGlobal) {
  20306. subMesh.updateBoundingInfo(matrix);
  20307. }
  20308. }
  20309. return this;
  20310. };
  20311. /** @hidden */
  20312. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20313. // Bounding info
  20314. this._updateBoundingInfo();
  20315. };
  20316. /**
  20317. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20318. * A mesh is in the frustum if its bounding box intersects the frustum
  20319. * @param frustumPlanes defines the frustum to test
  20320. * @returns true if the mesh is in the frustum planes
  20321. */
  20322. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20323. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20324. };
  20325. /**
  20326. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20327. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20328. * @param frustumPlanes defines the frustum to test
  20329. * @returns true if the mesh is completely in the frustum planes
  20330. */
  20331. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20332. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20333. };
  20334. /**
  20335. * True if the mesh intersects another mesh or a SolidParticle object
  20336. * @param mesh defines a target mesh or SolidParticle to test
  20337. * @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)
  20338. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20339. * @returns true if there is an intersection
  20340. */
  20341. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20342. if (precise === void 0) { precise = false; }
  20343. if (!this._boundingInfo || !mesh._boundingInfo) {
  20344. return false;
  20345. }
  20346. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20347. return true;
  20348. }
  20349. if (includeDescendants) {
  20350. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20351. var child = _a[_i];
  20352. if (child.intersectsMesh(mesh, precise, true)) {
  20353. return true;
  20354. }
  20355. }
  20356. }
  20357. return false;
  20358. };
  20359. /**
  20360. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20361. * @param point defines the point to test
  20362. * @returns true if there is an intersection
  20363. */
  20364. AbstractMesh.prototype.intersectsPoint = function (point) {
  20365. if (!this._boundingInfo) {
  20366. return false;
  20367. }
  20368. return this._boundingInfo.intersectsPoint(point);
  20369. };
  20370. /**
  20371. * Gets the current physics impostor
  20372. * @see http://doc.babylonjs.com/features/physics_engine
  20373. * @returns a physics impostor or null
  20374. */
  20375. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20376. return this.physicsImpostor;
  20377. };
  20378. /**
  20379. * Gets the position of the current mesh in camera space
  20380. * @param camera defines the camera to use
  20381. * @returns a position
  20382. */
  20383. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20384. if (camera === void 0) { camera = null; }
  20385. if (!camera) {
  20386. camera = this.getScene().activeCamera;
  20387. }
  20388. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20389. };
  20390. /**
  20391. * Returns the distance from the mesh to the active camera
  20392. * @param camera defines the camera to use
  20393. * @returns the distance
  20394. */
  20395. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20396. if (camera === void 0) { camera = null; }
  20397. if (!camera) {
  20398. camera = this.getScene().activeCamera;
  20399. }
  20400. return this.absolutePosition.subtract(camera.position).length();
  20401. };
  20402. /**
  20403. * Apply a physic impulse to the mesh
  20404. * @param force defines the force to apply
  20405. * @param contactPoint defines where to apply the force
  20406. * @returns the current mesh
  20407. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20408. */
  20409. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20410. if (!this.physicsImpostor) {
  20411. return this;
  20412. }
  20413. this.physicsImpostor.applyImpulse(force, contactPoint);
  20414. return this;
  20415. };
  20416. /**
  20417. * Creates a physic joint between two meshes
  20418. * @param otherMesh defines the other mesh to use
  20419. * @param pivot1 defines the pivot to use on this mesh
  20420. * @param pivot2 defines the pivot to use on the other mesh
  20421. * @param options defines additional options (can be plugin dependent)
  20422. * @returns the current mesh
  20423. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20424. */
  20425. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20426. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20427. return this;
  20428. }
  20429. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20430. mainPivot: pivot1,
  20431. connectedPivot: pivot2,
  20432. nativeParams: options
  20433. });
  20434. return this;
  20435. };
  20436. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20437. // Collisions
  20438. /**
  20439. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20440. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20441. */
  20442. get: function () {
  20443. return this._checkCollisions;
  20444. },
  20445. set: function (collisionEnabled) {
  20446. this._checkCollisions = collisionEnabled;
  20447. if (this.getScene().workerCollisions) {
  20448. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20449. }
  20450. },
  20451. enumerable: true,
  20452. configurable: true
  20453. });
  20454. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20455. /**
  20456. * Gets Collider object used to compute collisions (not physics)
  20457. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20458. */
  20459. get: function () {
  20460. return this._collider;
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. /**
  20466. * Move the mesh using collision engine
  20467. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20468. * @param displacement defines the requested displacement vector
  20469. * @returns the current mesh
  20470. */
  20471. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20472. var globalPosition = this.getAbsolutePosition();
  20473. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20474. if (!this._collider) {
  20475. this._collider = new BABYLON.Collider();
  20476. }
  20477. this._collider._radius = this.ellipsoid;
  20478. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20479. return this;
  20480. };
  20481. // Submeshes octree
  20482. /**
  20483. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20484. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20485. * @param maxCapacity defines the maximum size of each block (64 by default)
  20486. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20487. * @returns the new octree
  20488. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20489. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20490. */
  20491. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20492. if (maxCapacity === void 0) { maxCapacity = 64; }
  20493. if (maxDepth === void 0) { maxDepth = 2; }
  20494. if (!this._submeshesOctree) {
  20495. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20496. }
  20497. this.computeWorldMatrix(true);
  20498. var boundingInfo = this.getBoundingInfo();
  20499. // Update octree
  20500. var bbox = boundingInfo.boundingBox;
  20501. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20502. return this._submeshesOctree;
  20503. };
  20504. // Collisions
  20505. /** @hidden */
  20506. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20507. this._generatePointsArray();
  20508. if (!this._positions) {
  20509. return this;
  20510. }
  20511. // Transformation
  20512. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20513. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20514. subMesh._lastColliderWorldVertices = [];
  20515. subMesh._trianglePlanes = [];
  20516. var start = subMesh.verticesStart;
  20517. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20518. for (var i = start; i < end; i++) {
  20519. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20520. }
  20521. }
  20522. // Collide
  20523. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20524. if (collider.collisionFound) {
  20525. collider.collidedMesh = this;
  20526. }
  20527. return this;
  20528. };
  20529. /** @hidden */
  20530. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20531. var subMeshes;
  20532. var len;
  20533. // Octrees
  20534. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20535. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20536. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20537. len = intersections.length;
  20538. subMeshes = intersections.data;
  20539. }
  20540. else {
  20541. subMeshes = this.subMeshes;
  20542. len = subMeshes.length;
  20543. }
  20544. for (var index = 0; index < len; index++) {
  20545. var subMesh = subMeshes[index];
  20546. // Bounding test
  20547. if (len > 1 && !subMesh._checkCollision(collider))
  20548. continue;
  20549. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20550. }
  20551. return this;
  20552. };
  20553. /** @hidden */
  20554. AbstractMesh.prototype._checkCollision = function (collider) {
  20555. // Bounding box test
  20556. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20557. return this;
  20558. // Transformation matrix
  20559. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20560. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20561. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20562. return this;
  20563. };
  20564. // Picking
  20565. /** @hidden */
  20566. AbstractMesh.prototype._generatePointsArray = function () {
  20567. return false;
  20568. };
  20569. /**
  20570. * Checks if the passed Ray intersects with the mesh
  20571. * @param ray defines the ray to use
  20572. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20573. * @returns the picking info
  20574. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20575. */
  20576. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20577. var pickingInfo = new BABYLON.PickingInfo();
  20578. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20579. return pickingInfo;
  20580. }
  20581. if (!this._generatePointsArray()) {
  20582. return pickingInfo;
  20583. }
  20584. var intersectInfo = null;
  20585. // Octrees
  20586. var subMeshes;
  20587. var len;
  20588. if (this._submeshesOctree && this.useOctreeForPicking) {
  20589. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20590. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20591. len = intersections.length;
  20592. subMeshes = intersections.data;
  20593. }
  20594. else {
  20595. subMeshes = this.subMeshes;
  20596. len = subMeshes.length;
  20597. }
  20598. for (var index = 0; index < len; index++) {
  20599. var subMesh = subMeshes[index];
  20600. // Bounding test
  20601. if (len > 1 && !subMesh.canIntersects(ray))
  20602. continue;
  20603. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20604. if (currentIntersectInfo) {
  20605. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20606. intersectInfo = currentIntersectInfo;
  20607. intersectInfo.subMeshId = index;
  20608. if (fastCheck) {
  20609. break;
  20610. }
  20611. }
  20612. }
  20613. }
  20614. if (intersectInfo) {
  20615. // Get picked point
  20616. var world = this.getWorldMatrix();
  20617. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20618. var direction = ray.direction.clone();
  20619. direction = direction.scale(intersectInfo.distance);
  20620. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20621. var pickedPoint = worldOrigin.add(worldDirection);
  20622. // Return result
  20623. pickingInfo.hit = true;
  20624. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20625. pickingInfo.pickedPoint = pickedPoint;
  20626. pickingInfo.pickedMesh = this;
  20627. pickingInfo.bu = intersectInfo.bu || 0;
  20628. pickingInfo.bv = intersectInfo.bv || 0;
  20629. pickingInfo.faceId = intersectInfo.faceId;
  20630. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20631. return pickingInfo;
  20632. }
  20633. return pickingInfo;
  20634. };
  20635. /**
  20636. * Clones the current mesh
  20637. * @param name defines the mesh name
  20638. * @param newParent defines the new mesh parent
  20639. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20640. * @returns the new mesh
  20641. */
  20642. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20643. return null;
  20644. };
  20645. /**
  20646. * Disposes all the submeshes of the current meshnp
  20647. * @returns the current mesh
  20648. */
  20649. AbstractMesh.prototype.releaseSubMeshes = function () {
  20650. if (this.subMeshes) {
  20651. while (this.subMeshes.length) {
  20652. this.subMeshes[0].dispose();
  20653. }
  20654. }
  20655. else {
  20656. this.subMeshes = new Array();
  20657. }
  20658. return this;
  20659. };
  20660. /**
  20661. * Releases resources associated with this abstract mesh.
  20662. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20663. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20664. */
  20665. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20666. var _this = this;
  20667. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20668. var index;
  20669. // Smart Array Retainers.
  20670. this.getScene().freeActiveMeshes();
  20671. this.getScene().freeRenderingGroups();
  20672. // Action manager
  20673. if (this.actionManager !== undefined && this.actionManager !== null) {
  20674. this.actionManager.dispose();
  20675. this.actionManager = null;
  20676. }
  20677. // Skeleton
  20678. this._skeleton = null;
  20679. // Physics
  20680. if (this.physicsImpostor) {
  20681. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20682. }
  20683. // Intersections in progress
  20684. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20685. var other = this._intersectionsInProgress[index];
  20686. var pos = other._intersectionsInProgress.indexOf(this);
  20687. other._intersectionsInProgress.splice(pos, 1);
  20688. }
  20689. this._intersectionsInProgress = [];
  20690. // Lights
  20691. var lights = this.getScene().lights;
  20692. lights.forEach(function (light) {
  20693. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20694. if (meshIndex !== -1) {
  20695. light.includedOnlyMeshes.splice(meshIndex, 1);
  20696. }
  20697. meshIndex = light.excludedMeshes.indexOf(_this);
  20698. if (meshIndex !== -1) {
  20699. light.excludedMeshes.splice(meshIndex, 1);
  20700. }
  20701. // Shadow generators
  20702. var generator = light.getShadowGenerator();
  20703. if (generator) {
  20704. var shadowMap = generator.getShadowMap();
  20705. if (shadowMap && shadowMap.renderList) {
  20706. meshIndex = shadowMap.renderList.indexOf(_this);
  20707. if (meshIndex !== -1) {
  20708. shadowMap.renderList.splice(meshIndex, 1);
  20709. }
  20710. }
  20711. }
  20712. });
  20713. // Edges
  20714. if (this._edgesRenderer) {
  20715. this._edgesRenderer.dispose();
  20716. this._edgesRenderer = null;
  20717. }
  20718. // SubMeshes
  20719. if (this.getClassName() !== "InstancedMesh") {
  20720. this.releaseSubMeshes();
  20721. }
  20722. // Octree
  20723. var sceneOctree = this.getScene().selectionOctree;
  20724. if (sceneOctree !== undefined && sceneOctree !== null) {
  20725. var index = sceneOctree.dynamicContent.indexOf(this);
  20726. if (index !== -1) {
  20727. sceneOctree.dynamicContent.splice(index, 1);
  20728. }
  20729. }
  20730. // Query
  20731. var engine = this.getScene().getEngine();
  20732. if (this._occlusionQuery) {
  20733. this._isOcclusionQueryInProgress = false;
  20734. engine.deleteQuery(this._occlusionQuery);
  20735. this._occlusionQuery = null;
  20736. }
  20737. // Engine
  20738. engine.wipeCaches();
  20739. // Remove from scene
  20740. this.getScene().removeMesh(this);
  20741. if (disposeMaterialAndTextures) {
  20742. if (this.material) {
  20743. this.material.dispose(false, true);
  20744. }
  20745. }
  20746. if (!doNotRecurse) {
  20747. // Particles
  20748. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20749. if (this.getScene().particleSystems[index].emitter === this) {
  20750. this.getScene().particleSystems[index].dispose();
  20751. index--;
  20752. }
  20753. }
  20754. }
  20755. // facet data
  20756. if (this._facetDataEnabled) {
  20757. this.disableFacetData();
  20758. }
  20759. this.onAfterWorldMatrixUpdateObservable.clear();
  20760. this.onCollideObservable.clear();
  20761. this.onCollisionPositionChangeObservable.clear();
  20762. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20763. };
  20764. /**
  20765. * Adds the passed mesh as a child to the current mesh
  20766. * @param mesh defines the child mesh
  20767. * @returns the current mesh
  20768. */
  20769. AbstractMesh.prototype.addChild = function (mesh) {
  20770. mesh.setParent(this);
  20771. return this;
  20772. };
  20773. /**
  20774. * Removes the passed mesh from the current mesh children list
  20775. * @param mesh defines the child mesh
  20776. * @returns the current mesh
  20777. */
  20778. AbstractMesh.prototype.removeChild = function (mesh) {
  20779. mesh.setParent(null);
  20780. return this;
  20781. };
  20782. // Facet data
  20783. /** @hidden */
  20784. AbstractMesh.prototype._initFacetData = function () {
  20785. if (!this._facetNormals) {
  20786. this._facetNormals = new Array();
  20787. }
  20788. if (!this._facetPositions) {
  20789. this._facetPositions = new Array();
  20790. }
  20791. if (!this._facetPartitioning) {
  20792. this._facetPartitioning = new Array();
  20793. }
  20794. this._facetNb = (this.getIndices().length / 3) | 0;
  20795. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20796. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20797. for (var f = 0; f < this._facetNb; f++) {
  20798. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20799. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20800. }
  20801. this._facetDataEnabled = true;
  20802. return this;
  20803. };
  20804. /**
  20805. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20806. * This method can be called within the render loop.
  20807. * 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
  20808. * @returns the current mesh
  20809. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20810. */
  20811. AbstractMesh.prototype.updateFacetData = function () {
  20812. if (!this._facetDataEnabled) {
  20813. this._initFacetData();
  20814. }
  20815. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20816. var indices = this.getIndices();
  20817. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20818. var bInfo = this.getBoundingInfo();
  20819. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20820. // init arrays, matrix and sort function on first call
  20821. this._facetDepthSortEnabled = true;
  20822. if (indices instanceof Uint16Array) {
  20823. this._depthSortedIndices = new Uint16Array(indices);
  20824. }
  20825. else if (indices instanceof Uint32Array) {
  20826. this._depthSortedIndices = new Uint32Array(indices);
  20827. }
  20828. else {
  20829. var needs32bits = false;
  20830. for (var i = 0; i < indices.length; i++) {
  20831. if (indices[i] > 65535) {
  20832. needs32bits = true;
  20833. break;
  20834. }
  20835. }
  20836. if (needs32bits) {
  20837. this._depthSortedIndices = new Uint32Array(indices);
  20838. }
  20839. else {
  20840. this._depthSortedIndices = new Uint16Array(indices);
  20841. }
  20842. }
  20843. this._facetDepthSortFunction = function (f1, f2) {
  20844. return (f2.sqDistance - f1.sqDistance);
  20845. };
  20846. if (!this._facetDepthSortFrom) {
  20847. var camera = this.getScene().activeCamera;
  20848. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20849. }
  20850. this._depthSortedFacets = [];
  20851. for (var f = 0; f < this._facetNb; f++) {
  20852. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20853. this._depthSortedFacets.push(depthSortedFacet);
  20854. }
  20855. this._invertedMatrix = BABYLON.Matrix.Identity();
  20856. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20857. }
  20858. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20859. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20860. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20861. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20862. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20863. this._subDiv.max = this._partitioningSubdivisions;
  20864. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20865. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20866. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20867. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20868. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20869. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20870. // set the parameters for ComputeNormals()
  20871. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20872. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20873. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20874. this._facetParameters.bInfo = bInfo;
  20875. this._facetParameters.bbSize = this._bbSize;
  20876. this._facetParameters.subDiv = this._subDiv;
  20877. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20878. this._facetParameters.depthSort = this._facetDepthSort;
  20879. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20880. this.computeWorldMatrix(true);
  20881. this._worldMatrix.invertToRef(this._invertedMatrix);
  20882. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20883. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20884. }
  20885. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20886. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20887. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20888. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20889. var l = (this._depthSortedIndices.length / 3) | 0;
  20890. for (var f = 0; f < l; f++) {
  20891. var sind = this._depthSortedFacets[f].ind;
  20892. this._depthSortedIndices[f * 3] = indices[sind];
  20893. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20894. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20895. }
  20896. this.updateIndices(this._depthSortedIndices);
  20897. }
  20898. return this;
  20899. };
  20900. /**
  20901. * Returns the facetLocalNormals array.
  20902. * The normals are expressed in the mesh local spac
  20903. * @returns an array of Vector3
  20904. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20905. */
  20906. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20907. if (!this._facetNormals) {
  20908. this.updateFacetData();
  20909. }
  20910. return this._facetNormals;
  20911. };
  20912. /**
  20913. * Returns the facetLocalPositions array.
  20914. * The facet positions are expressed in the mesh local space
  20915. * @returns an array of Vector3
  20916. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20917. */
  20918. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20919. if (!this._facetPositions) {
  20920. this.updateFacetData();
  20921. }
  20922. return this._facetPositions;
  20923. };
  20924. /**
  20925. * Returns the facetLocalPartioning array
  20926. * @returns an array of array of numbers
  20927. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20928. */
  20929. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20930. if (!this._facetPartitioning) {
  20931. this.updateFacetData();
  20932. }
  20933. return this._facetPartitioning;
  20934. };
  20935. /**
  20936. * Returns the i-th facet position in the world system.
  20937. * This method allocates a new Vector3 per call
  20938. * @param i defines the facet index
  20939. * @returns a new Vector3
  20940. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20941. */
  20942. AbstractMesh.prototype.getFacetPosition = function (i) {
  20943. var pos = BABYLON.Vector3.Zero();
  20944. this.getFacetPositionToRef(i, pos);
  20945. return pos;
  20946. };
  20947. /**
  20948. * Sets the reference Vector3 with the i-th facet position in the world system
  20949. * @param i defines the facet index
  20950. * @param ref defines the target vector
  20951. * @returns the current mesh
  20952. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20953. */
  20954. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20955. var localPos = (this.getFacetLocalPositions())[i];
  20956. var world = this.getWorldMatrix();
  20957. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20958. return this;
  20959. };
  20960. /**
  20961. * Returns the i-th facet normal in the world system.
  20962. * This method allocates a new Vector3 per call
  20963. * @param i defines the facet index
  20964. * @returns a new Vector3
  20965. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20966. */
  20967. AbstractMesh.prototype.getFacetNormal = function (i) {
  20968. var norm = BABYLON.Vector3.Zero();
  20969. this.getFacetNormalToRef(i, norm);
  20970. return norm;
  20971. };
  20972. /**
  20973. * Sets the reference Vector3 with the i-th facet normal in the world system
  20974. * @param i defines the facet index
  20975. * @param ref defines the target vector
  20976. * @returns the current mesh
  20977. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20978. */
  20979. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20980. var localNorm = (this.getFacetLocalNormals())[i];
  20981. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20982. return this;
  20983. };
  20984. /**
  20985. * 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)
  20986. * @param x defines x coordinate
  20987. * @param y defines y coordinate
  20988. * @param z defines z coordinate
  20989. * @returns the array of facet indexes
  20990. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20991. */
  20992. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20993. var bInfo = this.getBoundingInfo();
  20994. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20995. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20996. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20997. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20998. return null;
  20999. }
  21000. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21001. };
  21002. /**
  21003. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21004. * @param projected sets as the (x,y,z) world projection on the facet
  21005. * @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
  21006. * @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
  21007. * @param x defines x coordinate
  21008. * @param y defines y coordinate
  21009. * @param z defines z coordinate
  21010. * @returns the face index if found (or null instead)
  21011. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21012. */
  21013. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21014. if (checkFace === void 0) { checkFace = false; }
  21015. if (facing === void 0) { facing = true; }
  21016. var world = this.getWorldMatrix();
  21017. var invMat = BABYLON.Tmp.Matrix[5];
  21018. world.invertToRef(invMat);
  21019. var invVect = BABYLON.Tmp.Vector3[8];
  21020. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21021. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21022. if (projected) {
  21023. // tranform the local computed projected vector to world coordinates
  21024. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21025. }
  21026. return closest;
  21027. };
  21028. /**
  21029. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21030. * @param projected sets as the (x,y,z) local projection on the facet
  21031. * @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
  21032. * @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
  21033. * @param x defines x coordinate
  21034. * @param y defines y coordinate
  21035. * @param z defines z coordinate
  21036. * @returns the face index if found (or null instead)
  21037. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21038. */
  21039. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21040. if (checkFace === void 0) { checkFace = false; }
  21041. if (facing === void 0) { facing = true; }
  21042. var closest = null;
  21043. var tmpx = 0.0;
  21044. var tmpy = 0.0;
  21045. var tmpz = 0.0;
  21046. var d = 0.0; // tmp dot facet normal * facet position
  21047. var t0 = 0.0;
  21048. var projx = 0.0;
  21049. var projy = 0.0;
  21050. var projz = 0.0;
  21051. // Get all the facets in the same partitioning block than (x, y, z)
  21052. var facetPositions = this.getFacetLocalPositions();
  21053. var facetNormals = this.getFacetLocalNormals();
  21054. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21055. if (!facetsInBlock) {
  21056. return null;
  21057. }
  21058. // Get the closest facet to (x, y, z)
  21059. var shortest = Number.MAX_VALUE; // init distance vars
  21060. var tmpDistance = shortest;
  21061. var fib; // current facet in the block
  21062. var norm; // current facet normal
  21063. var p0; // current facet barycenter position
  21064. // loop on all the facets in the current partitioning block
  21065. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21066. fib = facetsInBlock[idx];
  21067. norm = facetNormals[fib];
  21068. p0 = facetPositions[fib];
  21069. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21070. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21071. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21072. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21073. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21074. projx = x + norm.x * t0;
  21075. projy = y + norm.y * t0;
  21076. projz = z + norm.z * t0;
  21077. tmpx = projx - x;
  21078. tmpy = projy - y;
  21079. tmpz = projz - z;
  21080. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21081. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21082. shortest = tmpDistance;
  21083. closest = fib;
  21084. if (projected) {
  21085. projected.x = projx;
  21086. projected.y = projy;
  21087. projected.z = projz;
  21088. }
  21089. }
  21090. }
  21091. }
  21092. return closest;
  21093. };
  21094. /**
  21095. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21096. * @returns the parameters
  21097. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21098. */
  21099. AbstractMesh.prototype.getFacetDataParameters = function () {
  21100. return this._facetParameters;
  21101. };
  21102. /**
  21103. * Disables the feature FacetData and frees the related memory
  21104. * @returns the current mesh
  21105. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21106. */
  21107. AbstractMesh.prototype.disableFacetData = function () {
  21108. if (this._facetDataEnabled) {
  21109. this._facetDataEnabled = false;
  21110. this._facetPositions = new Array();
  21111. this._facetNormals = new Array();
  21112. this._facetPartitioning = new Array();
  21113. this._facetParameters = null;
  21114. this._depthSortedIndices = new Uint32Array(0);
  21115. }
  21116. return this;
  21117. };
  21118. /**
  21119. * Updates the AbstractMesh indices array
  21120. * @param indices defines the data source
  21121. * @returns the current mesh
  21122. */
  21123. AbstractMesh.prototype.updateIndices = function (indices) {
  21124. return this;
  21125. };
  21126. /**
  21127. * Creates new normals data for the mesh
  21128. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21129. * @returns the current mesh
  21130. */
  21131. AbstractMesh.prototype.createNormals = function (updatable) {
  21132. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21133. var indices = this.getIndices();
  21134. var normals;
  21135. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21136. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21137. }
  21138. else {
  21139. normals = [];
  21140. }
  21141. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21142. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21143. return this;
  21144. };
  21145. /**
  21146. * Align the mesh with a normal
  21147. * @param normal defines the normal to use
  21148. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21149. * @returns the current mesh
  21150. */
  21151. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21152. if (!upDirection) {
  21153. upDirection = BABYLON.Axis.Y;
  21154. }
  21155. var axisX = BABYLON.Tmp.Vector3[0];
  21156. var axisZ = BABYLON.Tmp.Vector3[1];
  21157. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21158. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21159. if (this.rotationQuaternion) {
  21160. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21161. }
  21162. else {
  21163. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21164. }
  21165. return this;
  21166. };
  21167. /** @hidden */
  21168. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21169. this._isOccluded = false;
  21170. };
  21171. /** No occlusion */
  21172. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21173. /** Occlusion set to optimisitic */
  21174. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21175. /** Occlusion set to strict */
  21176. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21177. /** Use an accurante occlusion algorithm */
  21178. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21179. /** Use a conservative occlusion algorithm */
  21180. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21181. return AbstractMesh;
  21182. }(BABYLON.TransformNode));
  21183. BABYLON.AbstractMesh = AbstractMesh;
  21184. })(BABYLON || (BABYLON = {}));
  21185. //# sourceMappingURL=babylon.abstractMesh.js.map
  21186. var BABYLON;
  21187. (function (BABYLON) {
  21188. /**
  21189. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21190. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21191. * 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.
  21192. */
  21193. var Light = /** @class */ (function (_super) {
  21194. __extends(Light, _super);
  21195. /**
  21196. * Creates a Light object in the scene.
  21197. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21198. * @param name The firendly name of the light
  21199. * @param scene The scene the light belongs too
  21200. */
  21201. function Light(name, scene) {
  21202. var _this = _super.call(this, name, scene) || this;
  21203. /**
  21204. * Diffuse gives the basic color to an object.
  21205. */
  21206. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21207. /**
  21208. * Specular produces a highlight color on an object.
  21209. * Note: This is note affecting PBR materials.
  21210. */
  21211. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21212. /**
  21213. * Strength of the light.
  21214. * Note: By default it is define in the framework own unit.
  21215. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21216. */
  21217. _this.intensity = 1.0;
  21218. /**
  21219. * Defines how far from the source the light is impacting in scene units.
  21220. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21221. */
  21222. _this.range = Number.MAX_VALUE;
  21223. /**
  21224. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21225. * of light.
  21226. */
  21227. _this._photometricScale = 1.0;
  21228. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21229. _this._radius = 0.00001;
  21230. /**
  21231. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21232. * exceeding the number allowed of the materials.
  21233. */
  21234. _this.renderPriority = 0;
  21235. _this._shadowEnabled = true;
  21236. _this._excludeWithLayerMask = 0;
  21237. _this._includeOnlyWithLayerMask = 0;
  21238. _this._lightmapMode = 0;
  21239. /**
  21240. * @hidden Internal use only.
  21241. */
  21242. _this._excludedMeshesIds = new Array();
  21243. /**
  21244. * @hidden Internal use only.
  21245. */
  21246. _this._includedOnlyMeshesIds = new Array();
  21247. _this.getScene().addLight(_this);
  21248. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21249. _this._buildUniformLayout();
  21250. _this.includedOnlyMeshes = new Array();
  21251. _this.excludedMeshes = new Array();
  21252. _this._resyncMeshes();
  21253. return _this;
  21254. }
  21255. Object.defineProperty(Light.prototype, "intensityMode", {
  21256. /**
  21257. * Gets the photometric scale used to interpret the intensity.
  21258. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21259. */
  21260. get: function () {
  21261. return this._intensityMode;
  21262. },
  21263. /**
  21264. * Sets the photometric scale used to interpret the intensity.
  21265. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21266. */
  21267. set: function (value) {
  21268. this._intensityMode = value;
  21269. this._computePhotometricScale();
  21270. },
  21271. enumerable: true,
  21272. configurable: true
  21273. });
  21274. ;
  21275. ;
  21276. Object.defineProperty(Light.prototype, "radius", {
  21277. /**
  21278. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21279. */
  21280. get: function () {
  21281. return this._radius;
  21282. },
  21283. /**
  21284. * sets the light radius used by PBR Materials to simulate soft area lights.
  21285. */
  21286. set: function (value) {
  21287. this._radius = value;
  21288. this._computePhotometricScale();
  21289. },
  21290. enumerable: true,
  21291. configurable: true
  21292. });
  21293. ;
  21294. ;
  21295. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21296. /**
  21297. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21298. * the current shadow generator.
  21299. */
  21300. get: function () {
  21301. return this._shadowEnabled;
  21302. },
  21303. /**
  21304. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21305. * the current shadow generator.
  21306. */
  21307. set: function (value) {
  21308. if (this._shadowEnabled === value) {
  21309. return;
  21310. }
  21311. this._shadowEnabled = value;
  21312. this._markMeshesAsLightDirty();
  21313. },
  21314. enumerable: true,
  21315. configurable: true
  21316. });
  21317. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21318. /**
  21319. * Gets the only meshes impacted by this light.
  21320. */
  21321. get: function () {
  21322. return this._includedOnlyMeshes;
  21323. },
  21324. /**
  21325. * Sets the only meshes impacted by this light.
  21326. */
  21327. set: function (value) {
  21328. this._includedOnlyMeshes = value;
  21329. this._hookArrayForIncludedOnly(value);
  21330. },
  21331. enumerable: true,
  21332. configurable: true
  21333. });
  21334. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21335. /**
  21336. * Gets the meshes not impacted by this light.
  21337. */
  21338. get: function () {
  21339. return this._excludedMeshes;
  21340. },
  21341. /**
  21342. * Sets the meshes not impacted by this light.
  21343. */
  21344. set: function (value) {
  21345. this._excludedMeshes = value;
  21346. this._hookArrayForExcluded(value);
  21347. },
  21348. enumerable: true,
  21349. configurable: true
  21350. });
  21351. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21352. /**
  21353. * Gets the layer id use to find what meshes are not impacted by the light.
  21354. * Inactive if 0
  21355. */
  21356. get: function () {
  21357. return this._excludeWithLayerMask;
  21358. },
  21359. /**
  21360. * Sets the layer id use to find what meshes are not impacted by the light.
  21361. * Inactive if 0
  21362. */
  21363. set: function (value) {
  21364. this._excludeWithLayerMask = value;
  21365. this._resyncMeshes();
  21366. },
  21367. enumerable: true,
  21368. configurable: true
  21369. });
  21370. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21371. /**
  21372. * Gets the layer id use to find what meshes are impacted by the light.
  21373. * Inactive if 0
  21374. */
  21375. get: function () {
  21376. return this._includeOnlyWithLayerMask;
  21377. },
  21378. /**
  21379. * Sets the layer id use to find what meshes are impacted by the light.
  21380. * Inactive if 0
  21381. */
  21382. set: function (value) {
  21383. this._includeOnlyWithLayerMask = value;
  21384. this._resyncMeshes();
  21385. },
  21386. enumerable: true,
  21387. configurable: true
  21388. });
  21389. Object.defineProperty(Light.prototype, "lightmapMode", {
  21390. /**
  21391. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21392. */
  21393. get: function () {
  21394. return this._lightmapMode;
  21395. },
  21396. /**
  21397. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21398. */
  21399. set: function (value) {
  21400. if (this._lightmapMode === value) {
  21401. return;
  21402. }
  21403. this._lightmapMode = value;
  21404. this._markMeshesAsLightDirty();
  21405. },
  21406. enumerable: true,
  21407. configurable: true
  21408. });
  21409. /**
  21410. * Returns the string "Light".
  21411. * @returns the class name
  21412. */
  21413. Light.prototype.getClassName = function () {
  21414. return "Light";
  21415. };
  21416. /**
  21417. * Converts the light information to a readable string for debug purpose.
  21418. * @param fullDetails Supports for multiple levels of logging within scene loading
  21419. * @returns the human readable light info
  21420. */
  21421. Light.prototype.toString = function (fullDetails) {
  21422. var ret = "Name: " + this.name;
  21423. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21424. if (this.animations) {
  21425. for (var i = 0; i < this.animations.length; i++) {
  21426. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21427. }
  21428. }
  21429. if (fullDetails) {
  21430. }
  21431. return ret;
  21432. };
  21433. /**
  21434. * Set the enabled state of this node.
  21435. * @param value - the new enabled state
  21436. */
  21437. Light.prototype.setEnabled = function (value) {
  21438. _super.prototype.setEnabled.call(this, value);
  21439. this._resyncMeshes();
  21440. };
  21441. /**
  21442. * Returns the Light associated shadow generator if any.
  21443. * @return the associated shadow generator.
  21444. */
  21445. Light.prototype.getShadowGenerator = function () {
  21446. return this._shadowGenerator;
  21447. };
  21448. /**
  21449. * Returns a Vector3, the absolute light position in the World.
  21450. * @returns the world space position of the light
  21451. */
  21452. Light.prototype.getAbsolutePosition = function () {
  21453. return BABYLON.Vector3.Zero();
  21454. };
  21455. /**
  21456. * Specifies if the light will affect the passed mesh.
  21457. * @param mesh The mesh to test against the light
  21458. * @return true the mesh is affected otherwise, false.
  21459. */
  21460. Light.prototype.canAffectMesh = function (mesh) {
  21461. if (!mesh) {
  21462. return true;
  21463. }
  21464. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21465. return false;
  21466. }
  21467. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21468. return false;
  21469. }
  21470. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21471. return false;
  21472. }
  21473. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21474. return false;
  21475. }
  21476. return true;
  21477. };
  21478. /**
  21479. * Computes and Returns the light World matrix.
  21480. * @returns the world matrix
  21481. */
  21482. Light.prototype.getWorldMatrix = function () {
  21483. this._currentRenderId = this.getScene().getRenderId();
  21484. this._childRenderId = this._currentRenderId;
  21485. var worldMatrix = this._getWorldMatrix();
  21486. if (this.parent && this.parent.getWorldMatrix) {
  21487. if (!this._parentedWorldMatrix) {
  21488. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21489. }
  21490. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21491. this._markSyncedWithParent();
  21492. return this._parentedWorldMatrix;
  21493. }
  21494. return worldMatrix;
  21495. };
  21496. /**
  21497. * Sort function to order lights for rendering.
  21498. * @param a First Light object to compare to second.
  21499. * @param b Second Light object to compare first.
  21500. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21501. */
  21502. Light.CompareLightsPriority = function (a, b) {
  21503. //shadow-casting lights have priority over non-shadow-casting lights
  21504. //the renderPrioirty is a secondary sort criterion
  21505. if (a.shadowEnabled !== b.shadowEnabled) {
  21506. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21507. }
  21508. return b.renderPriority - a.renderPriority;
  21509. };
  21510. /**
  21511. * Releases resources associated with this node.
  21512. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21513. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21514. */
  21515. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21516. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21517. if (this._shadowGenerator) {
  21518. this._shadowGenerator.dispose();
  21519. this._shadowGenerator = null;
  21520. }
  21521. // Animations
  21522. this.getScene().stopAnimation(this);
  21523. // Remove from meshes
  21524. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21525. var mesh = _a[_i];
  21526. mesh._removeLightSource(this);
  21527. }
  21528. this._uniformBuffer.dispose();
  21529. // Remove from scene
  21530. this.getScene().removeLight(this);
  21531. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21532. };
  21533. /**
  21534. * Returns the light type ID (integer).
  21535. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21536. */
  21537. Light.prototype.getTypeID = function () {
  21538. return 0;
  21539. };
  21540. /**
  21541. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21542. * @returns the scaled intensity in intensity mode unit
  21543. */
  21544. Light.prototype.getScaledIntensity = function () {
  21545. return this._photometricScale * this.intensity;
  21546. };
  21547. /**
  21548. * Returns a new Light object, named "name", from the current one.
  21549. * @param name The name of the cloned light
  21550. * @returns the new created light
  21551. */
  21552. Light.prototype.clone = function (name) {
  21553. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21554. if (!constructor) {
  21555. return null;
  21556. }
  21557. return BABYLON.SerializationHelper.Clone(constructor, this);
  21558. };
  21559. /**
  21560. * Serializes the current light into a Serialization object.
  21561. * @returns the serialized object.
  21562. */
  21563. Light.prototype.serialize = function () {
  21564. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21565. // Type
  21566. serializationObject.type = this.getTypeID();
  21567. // Parent
  21568. if (this.parent) {
  21569. serializationObject.parentId = this.parent.id;
  21570. }
  21571. // Inclusion / exclusions
  21572. if (this.excludedMeshes.length > 0) {
  21573. serializationObject.excludedMeshesIds = [];
  21574. this.excludedMeshes.forEach(function (mesh) {
  21575. serializationObject.excludedMeshesIds.push(mesh.id);
  21576. });
  21577. }
  21578. if (this.includedOnlyMeshes.length > 0) {
  21579. serializationObject.includedOnlyMeshesIds = [];
  21580. this.includedOnlyMeshes.forEach(function (mesh) {
  21581. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21582. });
  21583. }
  21584. // Animations
  21585. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21586. serializationObject.ranges = this.serializeAnimationRanges();
  21587. return serializationObject;
  21588. };
  21589. /**
  21590. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21591. * This new light is named "name" and added to the passed scene.
  21592. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21593. * @param name The friendly name of the light
  21594. * @param scene The scene the new light will belong to
  21595. * @returns the constructor function
  21596. */
  21597. Light.GetConstructorFromName = function (type, name, scene) {
  21598. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21599. if (constructorFunc) {
  21600. return constructorFunc;
  21601. }
  21602. // Default to no light for none present once.
  21603. return null;
  21604. };
  21605. /**
  21606. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21607. * @param parsedLight The JSON representation of the light
  21608. * @param scene The scene to create the parsed light in
  21609. * @returns the created light after parsing
  21610. */
  21611. Light.Parse = function (parsedLight, scene) {
  21612. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21613. if (!constructor) {
  21614. return null;
  21615. }
  21616. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21617. // Inclusion / exclusions
  21618. if (parsedLight.excludedMeshesIds) {
  21619. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21620. }
  21621. if (parsedLight.includedOnlyMeshesIds) {
  21622. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21623. }
  21624. // Parent
  21625. if (parsedLight.parentId) {
  21626. light._waitingParentId = parsedLight.parentId;
  21627. }
  21628. // Animations
  21629. if (parsedLight.animations) {
  21630. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21631. var parsedAnimation = parsedLight.animations[animationIndex];
  21632. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21633. }
  21634. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21635. }
  21636. if (parsedLight.autoAnimate) {
  21637. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21638. }
  21639. return light;
  21640. };
  21641. Light.prototype._hookArrayForExcluded = function (array) {
  21642. var _this = this;
  21643. var oldPush = array.push;
  21644. array.push = function () {
  21645. var items = [];
  21646. for (var _i = 0; _i < arguments.length; _i++) {
  21647. items[_i] = arguments[_i];
  21648. }
  21649. var result = oldPush.apply(array, items);
  21650. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21651. var item = items_1[_a];
  21652. item._resyncLighSource(_this);
  21653. }
  21654. return result;
  21655. };
  21656. var oldSplice = array.splice;
  21657. array.splice = function (index, deleteCount) {
  21658. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21659. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21660. var item = deleted_1[_i];
  21661. item._resyncLighSource(_this);
  21662. }
  21663. return deleted;
  21664. };
  21665. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21666. var item = array_1[_i];
  21667. item._resyncLighSource(this);
  21668. }
  21669. };
  21670. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21671. var _this = this;
  21672. var oldPush = array.push;
  21673. array.push = function () {
  21674. var items = [];
  21675. for (var _i = 0; _i < arguments.length; _i++) {
  21676. items[_i] = arguments[_i];
  21677. }
  21678. var result = oldPush.apply(array, items);
  21679. _this._resyncMeshes();
  21680. return result;
  21681. };
  21682. var oldSplice = array.splice;
  21683. array.splice = function (index, deleteCount) {
  21684. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21685. _this._resyncMeshes();
  21686. return deleted;
  21687. };
  21688. this._resyncMeshes();
  21689. };
  21690. Light.prototype._resyncMeshes = function () {
  21691. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21692. var mesh = _a[_i];
  21693. mesh._resyncLighSource(this);
  21694. }
  21695. };
  21696. /**
  21697. * Forces the meshes to update their light related information in their rendering used effects
  21698. * @hidden Internal Use Only
  21699. */
  21700. Light.prototype._markMeshesAsLightDirty = function () {
  21701. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21702. var mesh = _a[_i];
  21703. if (mesh._lightSources.indexOf(this) !== -1) {
  21704. mesh._markSubMeshesAsLightDirty();
  21705. }
  21706. }
  21707. };
  21708. /**
  21709. * Recomputes the cached photometric scale if needed.
  21710. */
  21711. Light.prototype._computePhotometricScale = function () {
  21712. this._photometricScale = this._getPhotometricScale();
  21713. this.getScene().resetCachedMaterial();
  21714. };
  21715. /**
  21716. * Returns the Photometric Scale according to the light type and intensity mode.
  21717. */
  21718. Light.prototype._getPhotometricScale = function () {
  21719. var photometricScale = 0.0;
  21720. var lightTypeID = this.getTypeID();
  21721. //get photometric mode
  21722. var photometricMode = this.intensityMode;
  21723. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21724. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21725. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21726. }
  21727. else {
  21728. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21729. }
  21730. }
  21731. //compute photometric scale
  21732. switch (lightTypeID) {
  21733. case Light.LIGHTTYPEID_POINTLIGHT:
  21734. case Light.LIGHTTYPEID_SPOTLIGHT:
  21735. switch (photometricMode) {
  21736. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21737. photometricScale = 1.0 / (4.0 * Math.PI);
  21738. break;
  21739. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21740. photometricScale = 1.0;
  21741. break;
  21742. case Light.INTENSITYMODE_LUMINANCE:
  21743. photometricScale = this.radius * this.radius;
  21744. break;
  21745. }
  21746. break;
  21747. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21748. switch (photometricMode) {
  21749. case Light.INTENSITYMODE_ILLUMINANCE:
  21750. photometricScale = 1.0;
  21751. break;
  21752. case Light.INTENSITYMODE_LUMINANCE:
  21753. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21754. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21755. var apexAngleRadians = this.radius;
  21756. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21757. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21758. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21759. photometricScale = solidAngle;
  21760. break;
  21761. }
  21762. break;
  21763. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21764. // No fall off in hemisperic light.
  21765. photometricScale = 1.0;
  21766. break;
  21767. }
  21768. return photometricScale;
  21769. };
  21770. /**
  21771. * Reorder the light in the scene according to their defined priority.
  21772. * @hidden Internal Use Only
  21773. */
  21774. Light.prototype._reorderLightsInScene = function () {
  21775. var scene = this.getScene();
  21776. if (this._renderPriority != 0) {
  21777. scene.requireLightSorting = true;
  21778. }
  21779. this.getScene().sortLightsByPriority();
  21780. };
  21781. //lightmapMode Consts
  21782. /**
  21783. * If every light affecting the material is in this lightmapMode,
  21784. * material.lightmapTexture adds or multiplies
  21785. * (depends on material.useLightmapAsShadowmap)
  21786. * after every other light calculations.
  21787. */
  21788. Light.LIGHTMAP_DEFAULT = 0;
  21789. /**
  21790. * material.lightmapTexture as only diffuse lighting from this light
  21791. * adds only specular lighting from this light
  21792. * adds dynamic shadows
  21793. */
  21794. Light.LIGHTMAP_SPECULAR = 1;
  21795. /**
  21796. * material.lightmapTexture as only lighting
  21797. * no light calculation from this light
  21798. * only adds dynamic shadows from this light
  21799. */
  21800. Light.LIGHTMAP_SHADOWSONLY = 2;
  21801. // Intensity Mode Consts
  21802. /**
  21803. * Each light type uses the default quantity according to its type:
  21804. * point/spot lights use luminous intensity
  21805. * directional lights use illuminance
  21806. */
  21807. Light.INTENSITYMODE_AUTOMATIC = 0;
  21808. /**
  21809. * lumen (lm)
  21810. */
  21811. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21812. /**
  21813. * candela (lm/sr)
  21814. */
  21815. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21816. /**
  21817. * lux (lm/m^2)
  21818. */
  21819. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21820. /**
  21821. * nit (cd/m^2)
  21822. */
  21823. Light.INTENSITYMODE_LUMINANCE = 4;
  21824. // Light types ids const.
  21825. /**
  21826. * Light type const id of the point light.
  21827. */
  21828. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21829. /**
  21830. * Light type const id of the directional light.
  21831. */
  21832. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21833. /**
  21834. * Light type const id of the spot light.
  21835. */
  21836. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21837. /**
  21838. * Light type const id of the hemispheric light.
  21839. */
  21840. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21841. __decorate([
  21842. BABYLON.serializeAsColor3()
  21843. ], Light.prototype, "diffuse", void 0);
  21844. __decorate([
  21845. BABYLON.serializeAsColor3()
  21846. ], Light.prototype, "specular", void 0);
  21847. __decorate([
  21848. BABYLON.serialize()
  21849. ], Light.prototype, "intensity", void 0);
  21850. __decorate([
  21851. BABYLON.serialize()
  21852. ], Light.prototype, "range", void 0);
  21853. __decorate([
  21854. BABYLON.serialize()
  21855. ], Light.prototype, "intensityMode", null);
  21856. __decorate([
  21857. BABYLON.serialize()
  21858. ], Light.prototype, "radius", null);
  21859. __decorate([
  21860. BABYLON.serialize()
  21861. ], Light.prototype, "_renderPriority", void 0);
  21862. __decorate([
  21863. BABYLON.expandToProperty("_reorderLightsInScene")
  21864. ], Light.prototype, "renderPriority", void 0);
  21865. __decorate([
  21866. BABYLON.serialize("shadowEnabled")
  21867. ], Light.prototype, "_shadowEnabled", void 0);
  21868. __decorate([
  21869. BABYLON.serialize("excludeWithLayerMask")
  21870. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21871. __decorate([
  21872. BABYLON.serialize("includeOnlyWithLayerMask")
  21873. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21874. __decorate([
  21875. BABYLON.serialize("lightmapMode")
  21876. ], Light.prototype, "_lightmapMode", void 0);
  21877. return Light;
  21878. }(BABYLON.Node));
  21879. BABYLON.Light = Light;
  21880. })(BABYLON || (BABYLON = {}));
  21881. //# sourceMappingURL=babylon.light.js.map
  21882. var BABYLON;
  21883. (function (BABYLON) {
  21884. var Camera = /** @class */ (function (_super) {
  21885. __extends(Camera, _super);
  21886. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21887. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21888. var _this = _super.call(this, name, scene) || this;
  21889. /**
  21890. * The vector the camera should consider as up.
  21891. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21892. */
  21893. _this.upVector = BABYLON.Vector3.Up();
  21894. _this.orthoLeft = null;
  21895. _this.orthoRight = null;
  21896. _this.orthoBottom = null;
  21897. _this.orthoTop = null;
  21898. /**
  21899. * FOV is set in Radians. (default is 0.8)
  21900. */
  21901. _this.fov = 0.8;
  21902. _this.minZ = 1;
  21903. _this.maxZ = 10000.0;
  21904. _this.inertia = 0.9;
  21905. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21906. _this.isIntermediate = false;
  21907. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21908. /**
  21909. * Restricts the camera to viewing objects with the same layerMask.
  21910. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21911. */
  21912. _this.layerMask = 0x0FFFFFFF;
  21913. /**
  21914. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21915. */
  21916. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21917. // Camera rig members
  21918. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21919. _this._rigCameras = new Array();
  21920. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21921. _this._skipRendering = false;
  21922. _this.customRenderTargets = new Array();
  21923. // Observables
  21924. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21925. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21926. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21927. _this.onRestoreStateObservable = new BABYLON.Observable();
  21928. // Cache
  21929. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21930. _this._projectionMatrix = new BABYLON.Matrix();
  21931. _this._doNotComputeProjectionMatrix = false;
  21932. _this._worldMatrix = BABYLON.Matrix.Identity();
  21933. _this._postProcesses = new Array();
  21934. _this._transformMatrix = BABYLON.Matrix.Zero();
  21935. _this._activeMeshes = new BABYLON.SmartArray(256);
  21936. _this._globalPosition = BABYLON.Vector3.Zero();
  21937. _this._refreshFrustumPlanes = true;
  21938. _this.getScene().addCamera(_this);
  21939. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21940. _this.getScene().activeCamera = _this;
  21941. }
  21942. _this.position = position;
  21943. return _this;
  21944. }
  21945. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21946. get: function () {
  21947. return Camera._PERSPECTIVE_CAMERA;
  21948. },
  21949. enumerable: true,
  21950. configurable: true
  21951. });
  21952. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21953. get: function () {
  21954. return Camera._ORTHOGRAPHIC_CAMERA;
  21955. },
  21956. enumerable: true,
  21957. configurable: true
  21958. });
  21959. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21960. /**
  21961. * This is the default FOV mode for perspective cameras.
  21962. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21963. *
  21964. */
  21965. get: function () {
  21966. return Camera._FOVMODE_VERTICAL_FIXED;
  21967. },
  21968. enumerable: true,
  21969. configurable: true
  21970. });
  21971. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21972. /**
  21973. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21974. *
  21975. */
  21976. get: function () {
  21977. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21978. },
  21979. enumerable: true,
  21980. configurable: true
  21981. });
  21982. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21983. get: function () {
  21984. return Camera._RIG_MODE_NONE;
  21985. },
  21986. enumerable: true,
  21987. configurable: true
  21988. });
  21989. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21990. get: function () {
  21991. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21992. },
  21993. enumerable: true,
  21994. configurable: true
  21995. });
  21996. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21997. get: function () {
  21998. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21999. },
  22000. enumerable: true,
  22001. configurable: true
  22002. });
  22003. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22004. get: function () {
  22005. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22006. },
  22007. enumerable: true,
  22008. configurable: true
  22009. });
  22010. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22011. get: function () {
  22012. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22013. },
  22014. enumerable: true,
  22015. configurable: true
  22016. });
  22017. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22018. get: function () {
  22019. return Camera._RIG_MODE_VR;
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22025. get: function () {
  22026. return Camera._RIG_MODE_WEBVR;
  22027. },
  22028. enumerable: true,
  22029. configurable: true
  22030. });
  22031. /**
  22032. * Store current camera state (fov, position, etc..)
  22033. */
  22034. Camera.prototype.storeState = function () {
  22035. this._stateStored = true;
  22036. this._storedFov = this.fov;
  22037. return this;
  22038. };
  22039. /**
  22040. * Restores the camera state values if it has been stored. You must call storeState() first
  22041. */
  22042. Camera.prototype._restoreStateValues = function () {
  22043. if (!this._stateStored) {
  22044. return false;
  22045. }
  22046. this.fov = this._storedFov;
  22047. return true;
  22048. };
  22049. /**
  22050. * Restored camera state. You must call storeState() first
  22051. */
  22052. Camera.prototype.restoreState = function () {
  22053. if (this._restoreStateValues()) {
  22054. this.onRestoreStateObservable.notifyObservers(this);
  22055. return true;
  22056. }
  22057. return false;
  22058. };
  22059. Camera.prototype.getClassName = function () {
  22060. return "Camera";
  22061. };
  22062. /**
  22063. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22064. */
  22065. Camera.prototype.toString = function (fullDetails) {
  22066. var ret = "Name: " + this.name;
  22067. ret += ", type: " + this.getClassName();
  22068. if (this.animations) {
  22069. for (var i = 0; i < this.animations.length; i++) {
  22070. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22071. }
  22072. }
  22073. if (fullDetails) {
  22074. }
  22075. return ret;
  22076. };
  22077. Object.defineProperty(Camera.prototype, "globalPosition", {
  22078. get: function () {
  22079. return this._globalPosition;
  22080. },
  22081. enumerable: true,
  22082. configurable: true
  22083. });
  22084. Camera.prototype.getActiveMeshes = function () {
  22085. return this._activeMeshes;
  22086. };
  22087. Camera.prototype.isActiveMesh = function (mesh) {
  22088. return (this._activeMeshes.indexOf(mesh) !== -1);
  22089. };
  22090. /**
  22091. * Is this camera ready to be used/rendered
  22092. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22093. * @return true if the camera is ready
  22094. */
  22095. Camera.prototype.isReady = function (completeCheck) {
  22096. if (completeCheck === void 0) { completeCheck = false; }
  22097. if (completeCheck) {
  22098. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22099. var pp = _a[_i];
  22100. if (pp && !pp.isReady()) {
  22101. return false;
  22102. }
  22103. }
  22104. }
  22105. return _super.prototype.isReady.call(this, completeCheck);
  22106. };
  22107. //Cache
  22108. Camera.prototype._initCache = function () {
  22109. _super.prototype._initCache.call(this);
  22110. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22111. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22112. this._cache.mode = undefined;
  22113. this._cache.minZ = undefined;
  22114. this._cache.maxZ = undefined;
  22115. this._cache.fov = undefined;
  22116. this._cache.fovMode = undefined;
  22117. this._cache.aspectRatio = undefined;
  22118. this._cache.orthoLeft = undefined;
  22119. this._cache.orthoRight = undefined;
  22120. this._cache.orthoBottom = undefined;
  22121. this._cache.orthoTop = undefined;
  22122. this._cache.renderWidth = undefined;
  22123. this._cache.renderHeight = undefined;
  22124. };
  22125. Camera.prototype._updateCache = function (ignoreParentClass) {
  22126. if (!ignoreParentClass) {
  22127. _super.prototype._updateCache.call(this);
  22128. }
  22129. this._cache.position.copyFrom(this.position);
  22130. this._cache.upVector.copyFrom(this.upVector);
  22131. };
  22132. // Synchronized
  22133. Camera.prototype._isSynchronized = function () {
  22134. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22135. };
  22136. Camera.prototype._isSynchronizedViewMatrix = function () {
  22137. if (!_super.prototype._isSynchronized.call(this))
  22138. return false;
  22139. return this._cache.position.equals(this.position)
  22140. && this._cache.upVector.equals(this.upVector)
  22141. && this.isSynchronizedWithParent();
  22142. };
  22143. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22144. var check = this._cache.mode === this.mode
  22145. && this._cache.minZ === this.minZ
  22146. && this._cache.maxZ === this.maxZ;
  22147. if (!check) {
  22148. return false;
  22149. }
  22150. var engine = this.getEngine();
  22151. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22152. check = this._cache.fov === this.fov
  22153. && this._cache.fovMode === this.fovMode
  22154. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22155. }
  22156. else {
  22157. check = this._cache.orthoLeft === this.orthoLeft
  22158. && this._cache.orthoRight === this.orthoRight
  22159. && this._cache.orthoBottom === this.orthoBottom
  22160. && this._cache.orthoTop === this.orthoTop
  22161. && this._cache.renderWidth === engine.getRenderWidth()
  22162. && this._cache.renderHeight === engine.getRenderHeight();
  22163. }
  22164. return check;
  22165. };
  22166. // Controls
  22167. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22168. };
  22169. Camera.prototype.detachControl = function (element) {
  22170. };
  22171. Camera.prototype.update = function () {
  22172. this._checkInputs();
  22173. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22174. this._updateRigCameras();
  22175. }
  22176. };
  22177. Camera.prototype._checkInputs = function () {
  22178. this.onAfterCheckInputsObservable.notifyObservers(this);
  22179. };
  22180. Object.defineProperty(Camera.prototype, "rigCameras", {
  22181. get: function () {
  22182. return this._rigCameras;
  22183. },
  22184. enumerable: true,
  22185. configurable: true
  22186. });
  22187. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22188. get: function () {
  22189. return this._rigPostProcess;
  22190. },
  22191. enumerable: true,
  22192. configurable: true
  22193. });
  22194. /**
  22195. * Internal, gets the first post proces.
  22196. * @returns the first post process to be run on this camera.
  22197. */
  22198. Camera.prototype._getFirstPostProcess = function () {
  22199. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22200. if (this._postProcesses[ppIndex] !== null) {
  22201. return this._postProcesses[ppIndex];
  22202. }
  22203. }
  22204. return null;
  22205. };
  22206. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22207. // invalidate framebuffer
  22208. var firstPostProcess = this._getFirstPostProcess();
  22209. if (firstPostProcess) {
  22210. firstPostProcess.markTextureDirty();
  22211. }
  22212. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22213. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22214. var cam = this._rigCameras[i];
  22215. var rigPostProcess = cam._rigPostProcess;
  22216. // for VR rig, there does not have to be a post process
  22217. if (rigPostProcess) {
  22218. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22219. if (isPass) {
  22220. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22221. cam.isIntermediate = this._postProcesses.length === 0;
  22222. }
  22223. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22224. rigPostProcess.markTextureDirty();
  22225. }
  22226. else {
  22227. cam._postProcesses = this._postProcesses.slice(0);
  22228. }
  22229. }
  22230. };
  22231. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22232. if (insertAt === void 0) { insertAt = null; }
  22233. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22234. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22235. return 0;
  22236. }
  22237. if (insertAt == null || insertAt < 0) {
  22238. this._postProcesses.push(postProcess);
  22239. }
  22240. else if (this._postProcesses[insertAt] === null) {
  22241. this._postProcesses[insertAt] = postProcess;
  22242. }
  22243. else {
  22244. this._postProcesses.splice(insertAt, 0, postProcess);
  22245. }
  22246. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22247. return this._postProcesses.indexOf(postProcess);
  22248. };
  22249. Camera.prototype.detachPostProcess = function (postProcess) {
  22250. var idx = this._postProcesses.indexOf(postProcess);
  22251. if (idx !== -1) {
  22252. this._postProcesses[idx] = null;
  22253. }
  22254. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22255. };
  22256. Camera.prototype.getWorldMatrix = function () {
  22257. if (this._isSynchronizedViewMatrix()) {
  22258. return this._worldMatrix;
  22259. }
  22260. // Getting the the view matrix will also compute the world matrix.
  22261. this.getViewMatrix();
  22262. return this._worldMatrix;
  22263. };
  22264. Camera.prototype._getViewMatrix = function () {
  22265. return BABYLON.Matrix.Identity();
  22266. };
  22267. Camera.prototype.getViewMatrix = function (force) {
  22268. if (!force && this._isSynchronizedViewMatrix()) {
  22269. return this._computedViewMatrix;
  22270. }
  22271. this.updateCache();
  22272. this._computedViewMatrix = this._getViewMatrix();
  22273. this._currentRenderId = this.getScene().getRenderId();
  22274. this._childRenderId = this._currentRenderId;
  22275. this._refreshFrustumPlanes = true;
  22276. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22277. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22278. }
  22279. this.onViewMatrixChangedObservable.notifyObservers(this);
  22280. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22281. return this._computedViewMatrix;
  22282. };
  22283. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22284. this._doNotComputeProjectionMatrix = true;
  22285. if (projection !== undefined) {
  22286. this._projectionMatrix = projection;
  22287. }
  22288. };
  22289. ;
  22290. Camera.prototype.unfreezeProjectionMatrix = function () {
  22291. this._doNotComputeProjectionMatrix = false;
  22292. };
  22293. ;
  22294. Camera.prototype.getProjectionMatrix = function (force) {
  22295. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22296. return this._projectionMatrix;
  22297. }
  22298. // Cache
  22299. this._cache.mode = this.mode;
  22300. this._cache.minZ = this.minZ;
  22301. this._cache.maxZ = this.maxZ;
  22302. // Matrix
  22303. this._refreshFrustumPlanes = true;
  22304. var engine = this.getEngine();
  22305. var scene = this.getScene();
  22306. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22307. this._cache.fov = this.fov;
  22308. this._cache.fovMode = this.fovMode;
  22309. this._cache.aspectRatio = engine.getAspectRatio(this);
  22310. if (this.minZ <= 0) {
  22311. this.minZ = 0.1;
  22312. }
  22313. if (scene.useRightHandedSystem) {
  22314. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22315. }
  22316. else {
  22317. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22318. }
  22319. }
  22320. else {
  22321. var halfWidth = engine.getRenderWidth() / 2.0;
  22322. var halfHeight = engine.getRenderHeight() / 2.0;
  22323. if (scene.useRightHandedSystem) {
  22324. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22325. }
  22326. else {
  22327. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22328. }
  22329. this._cache.orthoLeft = this.orthoLeft;
  22330. this._cache.orthoRight = this.orthoRight;
  22331. this._cache.orthoBottom = this.orthoBottom;
  22332. this._cache.orthoTop = this.orthoTop;
  22333. this._cache.renderWidth = engine.getRenderWidth();
  22334. this._cache.renderHeight = engine.getRenderHeight();
  22335. }
  22336. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22337. return this._projectionMatrix;
  22338. };
  22339. Camera.prototype.getTranformationMatrix = function () {
  22340. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22341. return this._transformMatrix;
  22342. };
  22343. Camera.prototype.updateFrustumPlanes = function () {
  22344. if (!this._refreshFrustumPlanes) {
  22345. return;
  22346. }
  22347. this.getTranformationMatrix();
  22348. if (!this._frustumPlanes) {
  22349. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22350. }
  22351. else {
  22352. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22353. }
  22354. this._refreshFrustumPlanes = false;
  22355. };
  22356. Camera.prototype.isInFrustum = function (target) {
  22357. this.updateFrustumPlanes();
  22358. return target.isInFrustum(this._frustumPlanes);
  22359. };
  22360. Camera.prototype.isCompletelyInFrustum = function (target) {
  22361. this.updateFrustumPlanes();
  22362. return target.isCompletelyInFrustum(this._frustumPlanes);
  22363. };
  22364. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22365. if (length === void 0) { length = 100; }
  22366. if (!transform) {
  22367. transform = this.getWorldMatrix();
  22368. }
  22369. if (!origin) {
  22370. origin = this.position;
  22371. }
  22372. var forward = new BABYLON.Vector3(0, 0, 1);
  22373. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22374. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22375. return new BABYLON.Ray(origin, direction, length);
  22376. };
  22377. /**
  22378. * Releases resources associated with this node.
  22379. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22380. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22381. */
  22382. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22383. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22384. // Observables
  22385. this.onViewMatrixChangedObservable.clear();
  22386. this.onProjectionMatrixChangedObservable.clear();
  22387. this.onAfterCheckInputsObservable.clear();
  22388. this.onRestoreStateObservable.clear();
  22389. // Inputs
  22390. if (this.inputs) {
  22391. this.inputs.clear();
  22392. }
  22393. // Animations
  22394. this.getScene().stopAnimation(this);
  22395. // Remove from scene
  22396. this.getScene().removeCamera(this);
  22397. while (this._rigCameras.length > 0) {
  22398. var camera = this._rigCameras.pop();
  22399. if (camera) {
  22400. camera.dispose();
  22401. }
  22402. }
  22403. // Postprocesses
  22404. if (this._rigPostProcess) {
  22405. this._rigPostProcess.dispose(this);
  22406. this._rigPostProcess = null;
  22407. this._postProcesses = [];
  22408. }
  22409. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22410. this._rigPostProcess = null;
  22411. this._postProcesses = [];
  22412. }
  22413. else {
  22414. var i = this._postProcesses.length;
  22415. while (--i >= 0) {
  22416. var postProcess = this._postProcesses[i];
  22417. if (postProcess) {
  22418. postProcess.dispose(this);
  22419. }
  22420. }
  22421. }
  22422. // Render targets
  22423. var i = this.customRenderTargets.length;
  22424. while (--i >= 0) {
  22425. this.customRenderTargets[i].dispose();
  22426. }
  22427. this.customRenderTargets = [];
  22428. // Active Meshes
  22429. this._activeMeshes.dispose();
  22430. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22431. };
  22432. Object.defineProperty(Camera.prototype, "leftCamera", {
  22433. // ---- Camera rigs section ----
  22434. get: function () {
  22435. if (this._rigCameras.length < 1) {
  22436. return null;
  22437. }
  22438. return this._rigCameras[0];
  22439. },
  22440. enumerable: true,
  22441. configurable: true
  22442. });
  22443. Object.defineProperty(Camera.prototype, "rightCamera", {
  22444. get: function () {
  22445. if (this._rigCameras.length < 2) {
  22446. return null;
  22447. }
  22448. return this._rigCameras[1];
  22449. },
  22450. enumerable: true,
  22451. configurable: true
  22452. });
  22453. Camera.prototype.getLeftTarget = function () {
  22454. if (this._rigCameras.length < 1) {
  22455. return null;
  22456. }
  22457. return this._rigCameras[0].getTarget();
  22458. };
  22459. Camera.prototype.getRightTarget = function () {
  22460. if (this._rigCameras.length < 2) {
  22461. return null;
  22462. }
  22463. return this._rigCameras[1].getTarget();
  22464. };
  22465. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22466. if (this.cameraRigMode === mode) {
  22467. return;
  22468. }
  22469. while (this._rigCameras.length > 0) {
  22470. var camera = this._rigCameras.pop();
  22471. if (camera) {
  22472. camera.dispose();
  22473. }
  22474. }
  22475. this.cameraRigMode = mode;
  22476. this._cameraRigParams = {};
  22477. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22478. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22479. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22480. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22481. // create the rig cameras, unless none
  22482. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22483. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22484. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22485. if (leftCamera && rightCamera) {
  22486. this._rigCameras.push(leftCamera);
  22487. this._rigCameras.push(rightCamera);
  22488. }
  22489. }
  22490. switch (this.cameraRigMode) {
  22491. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22492. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22493. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22494. break;
  22495. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22496. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22497. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22498. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22499. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22500. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22501. break;
  22502. case Camera.RIG_MODE_VR:
  22503. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22504. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22505. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22506. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22507. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22508. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22509. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22510. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22511. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22512. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22513. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22514. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22515. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22516. if (metrics.compensateDistortion) {
  22517. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22518. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22519. }
  22520. break;
  22521. case Camera.RIG_MODE_WEBVR:
  22522. if (rigParams.vrDisplay) {
  22523. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22524. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22525. //Left eye
  22526. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22527. this._rigCameras[0].setCameraRigParameter("left", true);
  22528. //leaving this for future reference
  22529. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22530. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22531. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22532. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22533. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22534. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22535. this._rigCameras[0].parent = this;
  22536. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22537. //Right eye
  22538. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22539. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22540. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22541. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22542. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22543. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22544. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22545. this._rigCameras[1].parent = this;
  22546. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22547. if (Camera.UseAlternateWebVRRendering) {
  22548. this._rigCameras[1]._skipRendering = true;
  22549. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22550. }
  22551. }
  22552. break;
  22553. }
  22554. this._cascadePostProcessesToRigCams();
  22555. this.update();
  22556. };
  22557. Camera.prototype._getVRProjectionMatrix = function () {
  22558. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22559. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22560. return this._projectionMatrix;
  22561. };
  22562. Camera.prototype._updateCameraRotationMatrix = function () {
  22563. //Here for WebVR
  22564. };
  22565. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22566. //Here for WebVR
  22567. };
  22568. /**
  22569. * This function MUST be overwritten by the different WebVR cameras available.
  22570. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22571. */
  22572. Camera.prototype._getWebVRProjectionMatrix = function () {
  22573. return BABYLON.Matrix.Identity();
  22574. };
  22575. /**
  22576. * This function MUST be overwritten by the different WebVR cameras available.
  22577. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22578. */
  22579. Camera.prototype._getWebVRViewMatrix = function () {
  22580. return BABYLON.Matrix.Identity();
  22581. };
  22582. Camera.prototype.setCameraRigParameter = function (name, value) {
  22583. if (!this._cameraRigParams) {
  22584. this._cameraRigParams = {};
  22585. }
  22586. this._cameraRigParams[name] = value;
  22587. //provisionnally:
  22588. if (name === "interaxialDistance") {
  22589. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22590. }
  22591. };
  22592. /**
  22593. * needs to be overridden by children so sub has required properties to be copied
  22594. */
  22595. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22596. return null;
  22597. };
  22598. /**
  22599. * May need to be overridden by children
  22600. */
  22601. Camera.prototype._updateRigCameras = function () {
  22602. for (var i = 0; i < this._rigCameras.length; i++) {
  22603. this._rigCameras[i].minZ = this.minZ;
  22604. this._rigCameras[i].maxZ = this.maxZ;
  22605. this._rigCameras[i].fov = this.fov;
  22606. }
  22607. // only update viewport when ANAGLYPH
  22608. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22609. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22610. }
  22611. };
  22612. Camera.prototype._setupInputs = function () {
  22613. };
  22614. Camera.prototype.serialize = function () {
  22615. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22616. // Type
  22617. serializationObject.type = this.getClassName();
  22618. // Parent
  22619. if (this.parent) {
  22620. serializationObject.parentId = this.parent.id;
  22621. }
  22622. if (this.inputs) {
  22623. this.inputs.serialize(serializationObject);
  22624. }
  22625. // Animations
  22626. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22627. serializationObject.ranges = this.serializeAnimationRanges();
  22628. return serializationObject;
  22629. };
  22630. Camera.prototype.clone = function (name) {
  22631. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22632. };
  22633. Camera.prototype.getDirection = function (localAxis) {
  22634. var result = BABYLON.Vector3.Zero();
  22635. this.getDirectionToRef(localAxis, result);
  22636. return result;
  22637. };
  22638. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22639. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22640. };
  22641. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22642. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22643. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22644. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22645. interaxial_distance: interaxial_distance,
  22646. isStereoscopicSideBySide: isStereoscopicSideBySide
  22647. });
  22648. if (constructorFunc) {
  22649. return constructorFunc;
  22650. }
  22651. // Default to universal camera
  22652. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22653. };
  22654. Camera.prototype.computeWorldMatrix = function () {
  22655. return this.getWorldMatrix();
  22656. };
  22657. Camera.Parse = function (parsedCamera, scene) {
  22658. var type = parsedCamera.type;
  22659. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22660. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22661. // Parent
  22662. if (parsedCamera.parentId) {
  22663. camera._waitingParentId = parsedCamera.parentId;
  22664. }
  22665. //If camera has an input manager, let it parse inputs settings
  22666. if (camera.inputs) {
  22667. camera.inputs.parse(parsedCamera);
  22668. camera._setupInputs();
  22669. }
  22670. if (camera.setPosition) { // need to force position
  22671. camera.position.copyFromFloats(0, 0, 0);
  22672. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22673. }
  22674. // Target
  22675. if (parsedCamera.target) {
  22676. if (camera.setTarget) {
  22677. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22678. }
  22679. }
  22680. // Apply 3d rig, when found
  22681. if (parsedCamera.cameraRigMode) {
  22682. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22683. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22684. }
  22685. // Animations
  22686. if (parsedCamera.animations) {
  22687. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22688. var parsedAnimation = parsedCamera.animations[animationIndex];
  22689. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22690. }
  22691. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22692. }
  22693. if (parsedCamera.autoAnimate) {
  22694. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22695. }
  22696. return camera;
  22697. };
  22698. // Statics
  22699. Camera._PERSPECTIVE_CAMERA = 0;
  22700. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22701. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22702. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22703. Camera._RIG_MODE_NONE = 0;
  22704. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22705. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22706. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22707. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22708. Camera._RIG_MODE_VR = 20;
  22709. Camera._RIG_MODE_WEBVR = 21;
  22710. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22711. Camera.UseAlternateWebVRRendering = false;
  22712. __decorate([
  22713. BABYLON.serializeAsVector3()
  22714. ], Camera.prototype, "position", void 0);
  22715. __decorate([
  22716. BABYLON.serializeAsVector3()
  22717. ], Camera.prototype, "upVector", void 0);
  22718. __decorate([
  22719. BABYLON.serialize()
  22720. ], Camera.prototype, "orthoLeft", void 0);
  22721. __decorate([
  22722. BABYLON.serialize()
  22723. ], Camera.prototype, "orthoRight", void 0);
  22724. __decorate([
  22725. BABYLON.serialize()
  22726. ], Camera.prototype, "orthoBottom", void 0);
  22727. __decorate([
  22728. BABYLON.serialize()
  22729. ], Camera.prototype, "orthoTop", void 0);
  22730. __decorate([
  22731. BABYLON.serialize()
  22732. ], Camera.prototype, "fov", void 0);
  22733. __decorate([
  22734. BABYLON.serialize()
  22735. ], Camera.prototype, "minZ", void 0);
  22736. __decorate([
  22737. BABYLON.serialize()
  22738. ], Camera.prototype, "maxZ", void 0);
  22739. __decorate([
  22740. BABYLON.serialize()
  22741. ], Camera.prototype, "inertia", void 0);
  22742. __decorate([
  22743. BABYLON.serialize()
  22744. ], Camera.prototype, "mode", void 0);
  22745. __decorate([
  22746. BABYLON.serialize()
  22747. ], Camera.prototype, "layerMask", void 0);
  22748. __decorate([
  22749. BABYLON.serialize()
  22750. ], Camera.prototype, "fovMode", void 0);
  22751. __decorate([
  22752. BABYLON.serialize()
  22753. ], Camera.prototype, "cameraRigMode", void 0);
  22754. __decorate([
  22755. BABYLON.serialize()
  22756. ], Camera.prototype, "interaxialDistance", void 0);
  22757. __decorate([
  22758. BABYLON.serialize()
  22759. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22760. return Camera;
  22761. }(BABYLON.Node));
  22762. BABYLON.Camera = Camera;
  22763. })(BABYLON || (BABYLON = {}));
  22764. //# sourceMappingURL=babylon.camera.js.map
  22765. var BABYLON;
  22766. (function (BABYLON) {
  22767. var RenderingManager = /** @class */ (function () {
  22768. function RenderingManager(scene) {
  22769. /**
  22770. * Hidden
  22771. */
  22772. this._useSceneAutoClearSetup = false;
  22773. this._renderingGroups = new Array();
  22774. this._autoClearDepthStencil = {};
  22775. this._customOpaqueSortCompareFn = {};
  22776. this._customAlphaTestSortCompareFn = {};
  22777. this._customTransparentSortCompareFn = {};
  22778. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  22779. this._scene = scene;
  22780. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22781. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22782. }
  22783. }
  22784. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22785. if (depth === void 0) { depth = true; }
  22786. if (stencil === void 0) { stencil = true; }
  22787. if (this._depthStencilBufferAlreadyCleaned) {
  22788. return;
  22789. }
  22790. this._scene.getEngine().clear(null, false, depth, stencil);
  22791. this._depthStencilBufferAlreadyCleaned = true;
  22792. };
  22793. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22794. // Update the observable context (not null as it only goes away on dispose)
  22795. var info = this._renderingGroupInfo;
  22796. info.scene = this._scene;
  22797. info.camera = this._scene.activeCamera;
  22798. // Dispatch sprites
  22799. if (renderSprites) {
  22800. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22801. var manager = this._scene.spriteManagers[index];
  22802. this.dispatchSprites(manager);
  22803. }
  22804. }
  22805. // Render
  22806. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22807. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22808. var renderingGroup = this._renderingGroups[index];
  22809. if (!renderingGroup)
  22810. continue;
  22811. var renderingGroupMask = Math.pow(2, index);
  22812. info.renderingGroupId = index;
  22813. // Before Observable
  22814. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22815. // Clear depth/stencil if needed
  22816. if (RenderingManager.AUTOCLEAR) {
  22817. var autoClear = this._useSceneAutoClearSetup ?
  22818. this._scene.getAutoClearDepthStencilSetup(index) :
  22819. this._autoClearDepthStencil[index];
  22820. if (autoClear && autoClear.autoClear) {
  22821. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22822. }
  22823. }
  22824. // Render
  22825. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22826. var step = _a[_i];
  22827. step.action(index);
  22828. }
  22829. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22830. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22831. var step = _c[_b];
  22832. step.action(index);
  22833. }
  22834. // After Observable
  22835. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22836. }
  22837. };
  22838. RenderingManager.prototype.reset = function () {
  22839. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22840. var renderingGroup = this._renderingGroups[index];
  22841. if (renderingGroup) {
  22842. renderingGroup.prepare();
  22843. }
  22844. }
  22845. };
  22846. RenderingManager.prototype.dispose = function () {
  22847. this.freeRenderingGroups();
  22848. this._renderingGroups.length = 0;
  22849. this._renderingGroupInfo = null;
  22850. };
  22851. /**
  22852. * Clear the info related to rendering groups preventing retention points during dispose.
  22853. */
  22854. RenderingManager.prototype.freeRenderingGroups = function () {
  22855. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22856. var renderingGroup = this._renderingGroups[index];
  22857. if (renderingGroup) {
  22858. renderingGroup.dispose();
  22859. }
  22860. }
  22861. };
  22862. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22863. if (this._renderingGroups[renderingGroupId] === undefined) {
  22864. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22865. }
  22866. };
  22867. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22868. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22869. this._prepareRenderingGroup(renderingGroupId);
  22870. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22871. };
  22872. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22873. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22874. this._prepareRenderingGroup(renderingGroupId);
  22875. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22876. };
  22877. /**
  22878. * @param subMesh The submesh to dispatch
  22879. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22880. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22881. */
  22882. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22883. if (mesh === undefined) {
  22884. mesh = subMesh.getMesh();
  22885. }
  22886. var renderingGroupId = mesh.renderingGroupId || 0;
  22887. this._prepareRenderingGroup(renderingGroupId);
  22888. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22889. };
  22890. /**
  22891. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22892. * This allowed control for front to back rendering or reversly depending of the special needs.
  22893. *
  22894. * @param renderingGroupId The rendering group id corresponding to its index
  22895. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22896. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22897. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22898. */
  22899. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22900. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22901. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22902. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22903. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22904. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22905. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22906. if (this._renderingGroups[renderingGroupId]) {
  22907. var group = this._renderingGroups[renderingGroupId];
  22908. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22909. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22910. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22911. }
  22912. };
  22913. /**
  22914. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22915. *
  22916. * @param renderingGroupId The rendering group id corresponding to its index
  22917. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22918. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22919. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22920. */
  22921. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22922. if (depth === void 0) { depth = true; }
  22923. if (stencil === void 0) { stencil = true; }
  22924. this._autoClearDepthStencil[renderingGroupId] = {
  22925. autoClear: autoClearDepthStencil,
  22926. depth: depth,
  22927. stencil: stencil
  22928. };
  22929. };
  22930. /**
  22931. * Gets the current auto clear configuration for one rendering group of the rendering
  22932. * manager.
  22933. * @param index the rendering group index to get the information for
  22934. * @returns The auto clear setup for the requested rendering group
  22935. */
  22936. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  22937. return this._autoClearDepthStencil[index];
  22938. };
  22939. /**
  22940. * The max id used for rendering groups (not included)
  22941. */
  22942. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22943. /**
  22944. * The min id used for rendering groups (included)
  22945. */
  22946. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22947. /**
  22948. * Used to globally prevent autoclearing scenes.
  22949. */
  22950. RenderingManager.AUTOCLEAR = true;
  22951. return RenderingManager;
  22952. }());
  22953. BABYLON.RenderingManager = RenderingManager;
  22954. })(BABYLON || (BABYLON = {}));
  22955. //# sourceMappingURL=babylon.renderingManager.js.map
  22956. var BABYLON;
  22957. (function (BABYLON) {
  22958. var RenderingGroup = /** @class */ (function () {
  22959. /**
  22960. * Creates a new rendering group.
  22961. * @param index The rendering group index
  22962. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22963. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22964. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22965. */
  22966. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22967. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22968. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22969. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22970. this.index = index;
  22971. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22972. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22973. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22974. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22975. this._particleSystems = new BABYLON.SmartArray(256);
  22976. this._spriteManagers = new BABYLON.SmartArray(256);
  22977. this._edgesRenderers = new BABYLON.SmartArray(16);
  22978. this._scene = scene;
  22979. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22980. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22981. this.transparentSortCompareFn = transparentSortCompareFn;
  22982. }
  22983. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22984. /**
  22985. * Set the opaque sort comparison function.
  22986. * If null the sub meshes will be render in the order they were created
  22987. */
  22988. set: function (value) {
  22989. this._opaqueSortCompareFn = value;
  22990. if (value) {
  22991. this._renderOpaque = this.renderOpaqueSorted;
  22992. }
  22993. else {
  22994. this._renderOpaque = RenderingGroup.renderUnsorted;
  22995. }
  22996. },
  22997. enumerable: true,
  22998. configurable: true
  22999. });
  23000. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23001. /**
  23002. * Set the alpha test sort comparison function.
  23003. * If null the sub meshes will be render in the order they were created
  23004. */
  23005. set: function (value) {
  23006. this._alphaTestSortCompareFn = value;
  23007. if (value) {
  23008. this._renderAlphaTest = this.renderAlphaTestSorted;
  23009. }
  23010. else {
  23011. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23012. }
  23013. },
  23014. enumerable: true,
  23015. configurable: true
  23016. });
  23017. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23018. /**
  23019. * Set the transparent sort comparison function.
  23020. * If null the sub meshes will be render in the order they were created
  23021. */
  23022. set: function (value) {
  23023. if (value) {
  23024. this._transparentSortCompareFn = value;
  23025. }
  23026. else {
  23027. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23028. }
  23029. this._renderTransparent = this.renderTransparentSorted;
  23030. },
  23031. enumerable: true,
  23032. configurable: true
  23033. });
  23034. /**
  23035. * Render all the sub meshes contained in the group.
  23036. * @param customRenderFunction Used to override the default render behaviour of the group.
  23037. * @returns true if rendered some submeshes.
  23038. */
  23039. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23040. if (customRenderFunction) {
  23041. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23042. return;
  23043. }
  23044. var engine = this._scene.getEngine();
  23045. // Depth only
  23046. if (this._depthOnlySubMeshes.length !== 0) {
  23047. engine.setColorWrite(false);
  23048. this._renderAlphaTest(this._depthOnlySubMeshes);
  23049. engine.setColorWrite(true);
  23050. }
  23051. // Opaque
  23052. if (this._opaqueSubMeshes.length !== 0) {
  23053. this._renderOpaque(this._opaqueSubMeshes);
  23054. }
  23055. // Alpha test
  23056. if (this._alphaTestSubMeshes.length !== 0) {
  23057. this._renderAlphaTest(this._alphaTestSubMeshes);
  23058. }
  23059. var stencilState = engine.getStencilBuffer();
  23060. engine.setStencilBuffer(false);
  23061. // Sprites
  23062. if (renderSprites) {
  23063. this._renderSprites();
  23064. }
  23065. // Particles
  23066. if (renderParticles) {
  23067. this._renderParticles(activeMeshes);
  23068. }
  23069. if (this.onBeforeTransparentRendering) {
  23070. this.onBeforeTransparentRendering();
  23071. }
  23072. // Transparent
  23073. if (this._transparentSubMeshes.length !== 0) {
  23074. this._renderTransparent(this._transparentSubMeshes);
  23075. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23076. }
  23077. // Set back stencil to false in case it changes before the edge renderer.
  23078. engine.setStencilBuffer(false);
  23079. // Edges
  23080. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23081. this._edgesRenderers.data[edgesRendererIndex].render();
  23082. }
  23083. // Restore Stencil state.
  23084. engine.setStencilBuffer(stencilState);
  23085. };
  23086. /**
  23087. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23088. * @param subMeshes The submeshes to render
  23089. */
  23090. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23091. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23092. };
  23093. /**
  23094. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23095. * @param subMeshes The submeshes to render
  23096. */
  23097. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23098. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23099. };
  23100. /**
  23101. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23102. * @param subMeshes The submeshes to render
  23103. */
  23104. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23105. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23106. };
  23107. /**
  23108. * Renders the submeshes in a specified order.
  23109. * @param subMeshes The submeshes to sort before render
  23110. * @param sortCompareFn The comparison function use to sort
  23111. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23112. * @param transparent Specifies to activate blending if true
  23113. */
  23114. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23115. var subIndex = 0;
  23116. var subMesh;
  23117. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23118. for (; subIndex < subMeshes.length; subIndex++) {
  23119. subMesh = subMeshes.data[subIndex];
  23120. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23121. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23122. }
  23123. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23124. if (sortCompareFn) {
  23125. sortedArray.sort(sortCompareFn);
  23126. }
  23127. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23128. subMesh = sortedArray[subIndex];
  23129. if (transparent) {
  23130. var material = subMesh.getMaterial();
  23131. if (material && material.needDepthPrePass) {
  23132. var engine = material.getScene().getEngine();
  23133. engine.setColorWrite(false);
  23134. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23135. subMesh.render(false);
  23136. engine.setColorWrite(true);
  23137. }
  23138. }
  23139. subMesh.render(transparent);
  23140. }
  23141. };
  23142. /**
  23143. * Renders the submeshes in the order they were dispatched (no sort applied).
  23144. * @param subMeshes The submeshes to render
  23145. */
  23146. RenderingGroup.renderUnsorted = function (subMeshes) {
  23147. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23148. var submesh = subMeshes.data[subIndex];
  23149. submesh.render(false);
  23150. }
  23151. };
  23152. /**
  23153. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23154. * are rendered back to front if in the same alpha index.
  23155. *
  23156. * @param a The first submesh
  23157. * @param b The second submesh
  23158. * @returns The result of the comparison
  23159. */
  23160. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23161. // Alpha index first
  23162. if (a._alphaIndex > b._alphaIndex) {
  23163. return 1;
  23164. }
  23165. if (a._alphaIndex < b._alphaIndex) {
  23166. return -1;
  23167. }
  23168. // Then distance to camera
  23169. return RenderingGroup.backToFrontSortCompare(a, b);
  23170. };
  23171. /**
  23172. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23173. * are rendered back to front.
  23174. *
  23175. * @param a The first submesh
  23176. * @param b The second submesh
  23177. * @returns The result of the comparison
  23178. */
  23179. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23180. // Then distance to camera
  23181. if (a._distanceToCamera < b._distanceToCamera) {
  23182. return 1;
  23183. }
  23184. if (a._distanceToCamera > b._distanceToCamera) {
  23185. return -1;
  23186. }
  23187. return 0;
  23188. };
  23189. /**
  23190. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23191. * are rendered front to back (prevent overdraw).
  23192. *
  23193. * @param a The first submesh
  23194. * @param b The second submesh
  23195. * @returns The result of the comparison
  23196. */
  23197. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23198. // Then distance to camera
  23199. if (a._distanceToCamera < b._distanceToCamera) {
  23200. return -1;
  23201. }
  23202. if (a._distanceToCamera > b._distanceToCamera) {
  23203. return 1;
  23204. }
  23205. return 0;
  23206. };
  23207. /**
  23208. * Resets the different lists of submeshes to prepare a new frame.
  23209. */
  23210. RenderingGroup.prototype.prepare = function () {
  23211. this._opaqueSubMeshes.reset();
  23212. this._transparentSubMeshes.reset();
  23213. this._alphaTestSubMeshes.reset();
  23214. this._depthOnlySubMeshes.reset();
  23215. this._particleSystems.reset();
  23216. this._spriteManagers.reset();
  23217. this._edgesRenderers.reset();
  23218. };
  23219. RenderingGroup.prototype.dispose = function () {
  23220. this._opaqueSubMeshes.dispose();
  23221. this._transparentSubMeshes.dispose();
  23222. this._alphaTestSubMeshes.dispose();
  23223. this._depthOnlySubMeshes.dispose();
  23224. this._particleSystems.dispose();
  23225. this._spriteManagers.dispose();
  23226. this._edgesRenderers.dispose();
  23227. };
  23228. /**
  23229. * Inserts the submesh in its correct queue depending on its material.
  23230. * @param subMesh The submesh to dispatch
  23231. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23232. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23233. */
  23234. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23235. // Get mesh and materials if not provided
  23236. if (mesh === undefined) {
  23237. mesh = subMesh.getMesh();
  23238. }
  23239. if (material === undefined) {
  23240. material = subMesh.getMaterial();
  23241. }
  23242. if (material === null || material === undefined) {
  23243. return;
  23244. }
  23245. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23246. this._transparentSubMeshes.push(subMesh);
  23247. }
  23248. else if (material.needAlphaTesting()) { // Alpha test
  23249. if (material.needDepthPrePass) {
  23250. this._depthOnlySubMeshes.push(subMesh);
  23251. }
  23252. this._alphaTestSubMeshes.push(subMesh);
  23253. }
  23254. else {
  23255. if (material.needDepthPrePass) {
  23256. this._depthOnlySubMeshes.push(subMesh);
  23257. }
  23258. this._opaqueSubMeshes.push(subMesh); // Opaque
  23259. }
  23260. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23261. this._edgesRenderers.push(mesh._edgesRenderer);
  23262. }
  23263. };
  23264. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23265. this._spriteManagers.push(spriteManager);
  23266. };
  23267. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23268. this._particleSystems.push(particleSystem);
  23269. };
  23270. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23271. if (this._particleSystems.length === 0) {
  23272. return;
  23273. }
  23274. // Particles
  23275. var activeCamera = this._scene.activeCamera;
  23276. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23277. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23278. var particleSystem = this._particleSystems.data[particleIndex];
  23279. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23280. continue;
  23281. }
  23282. var emitter = particleSystem.emitter;
  23283. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23284. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23285. }
  23286. }
  23287. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23288. };
  23289. RenderingGroup.prototype._renderSprites = function () {
  23290. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23291. return;
  23292. }
  23293. // Sprites
  23294. var activeCamera = this._scene.activeCamera;
  23295. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23296. for (var id = 0; id < this._spriteManagers.length; id++) {
  23297. var spriteManager = this._spriteManagers.data[id];
  23298. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23299. spriteManager.render();
  23300. }
  23301. }
  23302. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23303. };
  23304. return RenderingGroup;
  23305. }());
  23306. BABYLON.RenderingGroup = RenderingGroup;
  23307. })(BABYLON || (BABYLON = {}));
  23308. //# sourceMappingURL=babylon.renderingGroup.js.map
  23309. var BABYLON;
  23310. (function (BABYLON) {
  23311. /**
  23312. * Groups all the scene component constants in one place to ease maintenance.
  23313. * @hidden
  23314. */
  23315. var SceneComponentConstants = /** @class */ (function () {
  23316. function SceneComponentConstants() {
  23317. }
  23318. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23319. SceneComponentConstants.NAME_LAYER = "Layer";
  23320. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23321. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23322. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23323. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23324. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23325. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23326. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23327. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23328. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23329. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23330. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23331. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23332. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23333. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23334. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23335. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23336. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23337. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23338. return SceneComponentConstants;
  23339. }());
  23340. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23341. /**
  23342. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23343. * @hidden
  23344. */
  23345. var Stage = /** @class */ (function (_super) {
  23346. __extends(Stage, _super);
  23347. /**
  23348. * Hide ctor from the rest of the world.
  23349. * @param items The items to add.
  23350. */
  23351. function Stage(items) {
  23352. return _super.apply(this, items) || this;
  23353. }
  23354. /**
  23355. * Creates a new Stage.
  23356. * @returns A new instance of a Stage
  23357. */
  23358. Stage.Create = function () {
  23359. return Object.create(Stage.prototype);
  23360. };
  23361. /**
  23362. * Registers a step in an ordered way in the targeted stage.
  23363. * @param index Defines the position to register the step in
  23364. * @param component Defines the component attached to the step
  23365. * @param action Defines the action to launch during the step
  23366. */
  23367. Stage.prototype.registerStep = function (index, component, action) {
  23368. var i = 0;
  23369. var maxIndex = Number.MAX_VALUE;
  23370. for (; i < this.length && i < maxIndex; i++) {
  23371. var step = this[i];
  23372. maxIndex = step.index;
  23373. }
  23374. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23375. };
  23376. /**
  23377. * Clears all the steps from the stage.
  23378. */
  23379. Stage.prototype.clear = function () {
  23380. this.length = 0;
  23381. };
  23382. return Stage;
  23383. }(Array));
  23384. BABYLON.Stage = Stage;
  23385. })(BABYLON || (BABYLON = {}));
  23386. //# sourceMappingURL=babylon.sceneComponent.js.map
  23387. var BABYLON;
  23388. (function (BABYLON) {
  23389. /**
  23390. * Base class of the scene acting as a container for the different elements composing a scene.
  23391. * This class is dynamically extended by the different components of the scene increasing
  23392. * flexibility and reducing coupling
  23393. */
  23394. var AbstractScene = /** @class */ (function () {
  23395. function AbstractScene() {
  23396. /** All of the cameras added to this scene
  23397. * @see http://doc.babylonjs.com/babylon101/cameras
  23398. */
  23399. this.cameras = new Array();
  23400. /**
  23401. * All of the lights added to this scene
  23402. * @see http://doc.babylonjs.com/babylon101/lights
  23403. */
  23404. this.lights = new Array();
  23405. /**
  23406. * All of the (abstract) meshes added to this scene
  23407. */
  23408. this.meshes = new Array();
  23409. /**
  23410. * The list of skeletons added to the scene
  23411. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23412. */
  23413. this.skeletons = new Array();
  23414. /**
  23415. * All of the particle systems added to this scene
  23416. * @see http://doc.babylonjs.com/babylon101/particles
  23417. */
  23418. this.particleSystems = new Array();
  23419. /**
  23420. * Gets a list of Animations associated with the scene
  23421. */
  23422. this.animations = [];
  23423. /**
  23424. * All of the animation groups added to this scene
  23425. * @see http://doc.babylonjs.com/how_to/group
  23426. */
  23427. this.animationGroups = new Array();
  23428. /**
  23429. * All of the multi-materials added to this scene
  23430. * @see http://doc.babylonjs.com/how_to/multi_materials
  23431. */
  23432. this.multiMaterials = new Array();
  23433. /**
  23434. * All of the materials added to this scene
  23435. * @see http://doc.babylonjs.com/babylon101/materials
  23436. */
  23437. this.materials = new Array();
  23438. /**
  23439. * The list of morph target managers added to the scene
  23440. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23441. */
  23442. this.morphTargetManagers = new Array();
  23443. /**
  23444. * The list of geometries used in the scene.
  23445. */
  23446. this.geometries = new Array();
  23447. /**
  23448. * All of the tranform nodes added to this scene
  23449. * @see http://doc.babylonjs.com/how_to/transformnode
  23450. */
  23451. this.transformNodes = new Array();
  23452. /**
  23453. * ActionManagers available on the scene.
  23454. */
  23455. this.actionManagers = new Array();
  23456. /**
  23457. * Sounds to keep.
  23458. */
  23459. this.sounds = new Array();
  23460. /**
  23461. * Textures to keep.
  23462. */
  23463. this.textures = new Array();
  23464. }
  23465. /**
  23466. * Adds a parser in the list of available ones
  23467. * @param name Defines the name of the parser
  23468. * @param parser Defines the parser to add
  23469. */
  23470. AbstractScene.AddParser = function (name, parser) {
  23471. this._BabylonFileParsers[name] = parser;
  23472. };
  23473. /**
  23474. * Gets a general parser from the list of avaialble ones
  23475. * @param name Defines the name of the parser
  23476. * @returns the requested parser or null
  23477. */
  23478. AbstractScene.GetParser = function (name) {
  23479. if (this._BabylonFileParsers[name]) {
  23480. return this._BabylonFileParsers[name];
  23481. }
  23482. return null;
  23483. };
  23484. /**
  23485. * Adds n individual parser in the list of available ones
  23486. * @param name Defines the name of the parser
  23487. * @param parser Defines the parser to add
  23488. */
  23489. AbstractScene.AddIndividualParser = function (name, parser) {
  23490. this._IndividualBabylonFileParsers[name] = parser;
  23491. };
  23492. /**
  23493. * Gets an individual parser from the list of avaialble ones
  23494. * @param name Defines the name of the parser
  23495. * @returns the requested parser or null
  23496. */
  23497. AbstractScene.GetIndividualParser = function (name) {
  23498. if (this._IndividualBabylonFileParsers[name]) {
  23499. return this._IndividualBabylonFileParsers[name];
  23500. }
  23501. return null;
  23502. };
  23503. /**
  23504. * Parser json data and populate both a scene and its associated container object
  23505. * @param jsonData Defines the data to parse
  23506. * @param scene Defines the scene to parse the data for
  23507. * @param container Defines the container attached to the parsing sequence
  23508. * @param rootUrl Defines the root url of the data
  23509. */
  23510. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23511. for (var parserName in this._BabylonFileParsers) {
  23512. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23513. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23514. }
  23515. }
  23516. };
  23517. /**
  23518. * Stores the list of available parsers in the application.
  23519. */
  23520. AbstractScene._BabylonFileParsers = {};
  23521. /**
  23522. * Stores the list of available individual parsers in the application.
  23523. */
  23524. AbstractScene._IndividualBabylonFileParsers = {};
  23525. return AbstractScene;
  23526. }());
  23527. BABYLON.AbstractScene = AbstractScene;
  23528. })(BABYLON || (BABYLON = {}));
  23529. //# sourceMappingURL=babylon.abstractScene.js.map
  23530. var BABYLON;
  23531. (function (BABYLON) {
  23532. /** @hidden */
  23533. var ClickInfo = /** @class */ (function () {
  23534. function ClickInfo() {
  23535. this._singleClick = false;
  23536. this._doubleClick = false;
  23537. this._hasSwiped = false;
  23538. this._ignore = false;
  23539. }
  23540. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23541. get: function () {
  23542. return this._singleClick;
  23543. },
  23544. set: function (b) {
  23545. this._singleClick = b;
  23546. },
  23547. enumerable: true,
  23548. configurable: true
  23549. });
  23550. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23551. get: function () {
  23552. return this._doubleClick;
  23553. },
  23554. set: function (b) {
  23555. this._doubleClick = b;
  23556. },
  23557. enumerable: true,
  23558. configurable: true
  23559. });
  23560. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23561. get: function () {
  23562. return this._hasSwiped;
  23563. },
  23564. set: function (b) {
  23565. this._hasSwiped = b;
  23566. },
  23567. enumerable: true,
  23568. configurable: true
  23569. });
  23570. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23571. get: function () {
  23572. return this._ignore;
  23573. },
  23574. set: function (b) {
  23575. this._ignore = b;
  23576. },
  23577. enumerable: true,
  23578. configurable: true
  23579. });
  23580. return ClickInfo;
  23581. }());
  23582. /**
  23583. * This class is used by the onRenderingGroupObservable
  23584. */
  23585. var RenderingGroupInfo = /** @class */ (function () {
  23586. function RenderingGroupInfo() {
  23587. }
  23588. return RenderingGroupInfo;
  23589. }());
  23590. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23591. /**
  23592. * Represents a scene to be rendered by the engine.
  23593. * @see http://doc.babylonjs.com/features/scene
  23594. */
  23595. var Scene = /** @class */ (function (_super) {
  23596. __extends(Scene, _super);
  23597. /**
  23598. * Creates a new Scene
  23599. * @param engine defines the engine to use to render this scene
  23600. */
  23601. function Scene(engine) {
  23602. var _this = _super.call(this) || this;
  23603. // Members
  23604. /**
  23605. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23606. */
  23607. _this.autoClear = true;
  23608. /**
  23609. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23610. */
  23611. _this.autoClearDepthAndStencil = true;
  23612. /**
  23613. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23614. */
  23615. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23616. /**
  23617. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23618. */
  23619. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23620. _this._forceWireframe = false;
  23621. _this._forcePointsCloud = false;
  23622. /**
  23623. * Gets or sets a boolean indicating if animations are enabled
  23624. */
  23625. _this.animationsEnabled = true;
  23626. _this._animationPropertiesOverride = null;
  23627. /**
  23628. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23629. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23630. */
  23631. _this.useConstantAnimationDeltaTime = false;
  23632. /**
  23633. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23634. * Please note that it requires to run a ray cast through the scene on every frame
  23635. */
  23636. _this.constantlyUpdateMeshUnderPointer = false;
  23637. /**
  23638. * Defines the HTML cursor to use when hovering over interactive elements
  23639. */
  23640. _this.hoverCursor = "pointer";
  23641. /**
  23642. * Defines the HTML default cursor to use (empty by default)
  23643. */
  23644. _this.defaultCursor = "";
  23645. /**
  23646. * This is used to call preventDefault() on pointer down
  23647. * in order to block unwanted artifacts like system double clicks
  23648. */
  23649. _this.preventDefaultOnPointerDown = true;
  23650. // Metadata
  23651. /**
  23652. * Gets or sets user defined metadata
  23653. */
  23654. _this.metadata = null;
  23655. /**
  23656. * Use this array to add regular expressions used to disable offline support for specific urls
  23657. */
  23658. _this.disableOfflineSupportExceptionRules = new Array();
  23659. /**
  23660. * An event triggered when the scene is disposed.
  23661. */
  23662. _this.onDisposeObservable = new BABYLON.Observable();
  23663. _this._onDisposeObserver = null;
  23664. /**
  23665. * An event triggered before rendering the scene (right after animations and physics)
  23666. */
  23667. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23668. _this._onBeforeRenderObserver = null;
  23669. /**
  23670. * An event triggered after rendering the scene
  23671. */
  23672. _this.onAfterRenderObservable = new BABYLON.Observable();
  23673. _this._onAfterRenderObserver = null;
  23674. /**
  23675. * An event triggered before animating the scene
  23676. */
  23677. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23678. /**
  23679. * An event triggered after animations processing
  23680. */
  23681. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23682. /**
  23683. * An event triggered before draw calls are ready to be sent
  23684. */
  23685. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23686. /**
  23687. * An event triggered after draw calls have been sent
  23688. */
  23689. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23690. /**
  23691. * An event triggered when physic simulation is about to be run
  23692. */
  23693. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23694. /**
  23695. * An event triggered when physic simulation has been done
  23696. */
  23697. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23698. /**
  23699. * An event triggered when the scene is ready
  23700. */
  23701. _this.onReadyObservable = new BABYLON.Observable();
  23702. /**
  23703. * An event triggered before rendering a camera
  23704. */
  23705. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23706. _this._onBeforeCameraRenderObserver = null;
  23707. /**
  23708. * An event triggered after rendering a camera
  23709. */
  23710. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23711. _this._onAfterCameraRenderObserver = null;
  23712. /**
  23713. * An event triggered when active meshes evaluation is about to start
  23714. */
  23715. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23716. /**
  23717. * An event triggered when active meshes evaluation is done
  23718. */
  23719. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23720. /**
  23721. * An event triggered when particles rendering is about to start
  23722. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23723. */
  23724. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23725. /**
  23726. * An event triggered when particles rendering is done
  23727. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23728. */
  23729. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23730. /**
  23731. * An event triggered when sprites rendering is about to start
  23732. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23733. */
  23734. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23735. /**
  23736. * An event triggered when sprites rendering is done
  23737. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23738. */
  23739. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23740. /**
  23741. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23742. */
  23743. _this.onDataLoadedObservable = new BABYLON.Observable();
  23744. /**
  23745. * An event triggered when a camera is created
  23746. */
  23747. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23748. /**
  23749. * An event triggered when a camera is removed
  23750. */
  23751. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23752. /**
  23753. * An event triggered when a light is created
  23754. */
  23755. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23756. /**
  23757. * An event triggered when a light is removed
  23758. */
  23759. _this.onLightRemovedObservable = new BABYLON.Observable();
  23760. /**
  23761. * An event triggered when a geometry is created
  23762. */
  23763. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23764. /**
  23765. * An event triggered when a geometry is removed
  23766. */
  23767. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23768. /**
  23769. * An event triggered when a transform node is created
  23770. */
  23771. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23772. /**
  23773. * An event triggered when a transform node is removed
  23774. */
  23775. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23776. /**
  23777. * An event triggered when a mesh is created
  23778. */
  23779. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23780. /**
  23781. * An event triggered when a mesh is removed
  23782. */
  23783. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23784. /**
  23785. * An event triggered when render targets are about to be rendered
  23786. * Can happen multiple times per frame.
  23787. */
  23788. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23789. /**
  23790. * An event triggered when render targets were rendered.
  23791. * Can happen multiple times per frame.
  23792. */
  23793. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23794. /**
  23795. * An event triggered before calculating deterministic simulation step
  23796. */
  23797. _this.onBeforeStepObservable = new BABYLON.Observable();
  23798. /**
  23799. * An event triggered after calculating deterministic simulation step
  23800. */
  23801. _this.onAfterStepObservable = new BABYLON.Observable();
  23802. /**
  23803. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  23804. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23805. * 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)
  23806. */
  23807. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  23808. /**
  23809. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  23810. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23811. * 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)
  23812. */
  23813. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  23814. // Animations
  23815. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23816. /**
  23817. * 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).
  23818. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23819. */
  23820. _this.onPrePointerObservable = new BABYLON.Observable();
  23821. /**
  23822. * Observable event triggered each time an input event is received from the rendering canvas
  23823. */
  23824. _this.onPointerObservable = new BABYLON.Observable();
  23825. _this._meshPickProceed = false;
  23826. _this._currentPickResult = null;
  23827. _this._previousPickResult = null;
  23828. _this._totalPointersPressed = 0;
  23829. _this._doubleClickOccured = false;
  23830. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23831. _this.cameraToUseForPointers = null;
  23832. _this._pointerX = 0;
  23833. _this._pointerY = 0;
  23834. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23835. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23836. _this._startingPointerTime = 0;
  23837. _this._previousStartingPointerTime = 0;
  23838. _this._pointerCaptures = {};
  23839. // Deterministic lockstep
  23840. _this._timeAccumulator = 0;
  23841. _this._currentStepId = 0;
  23842. _this._currentInternalStep = 0;
  23843. // Keyboard
  23844. /**
  23845. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23846. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23847. */
  23848. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23849. /**
  23850. * Observable event triggered each time an keyboard event is received from the hosting window
  23851. */
  23852. _this.onKeyboardObservable = new BABYLON.Observable();
  23853. // Coordinates system
  23854. _this._useRightHandedSystem = false;
  23855. // Fog
  23856. _this._fogEnabled = true;
  23857. _this._fogMode = Scene.FOGMODE_NONE;
  23858. /**
  23859. * Gets or sets the fog color to use
  23860. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23861. */
  23862. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23863. /**
  23864. * Gets or sets the fog density to use
  23865. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23866. */
  23867. _this.fogDensity = 0.1;
  23868. /**
  23869. * Gets or sets the fog start distance to use
  23870. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23871. */
  23872. _this.fogStart = 0;
  23873. /**
  23874. * Gets or sets the fog end distance to use
  23875. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23876. */
  23877. _this.fogEnd = 1000.0;
  23878. // Lights
  23879. _this._shadowsEnabled = true;
  23880. _this._lightsEnabled = true;
  23881. /** All of the active cameras added to this scene. */
  23882. _this.activeCameras = new Array();
  23883. // Textures
  23884. _this._texturesEnabled = true;
  23885. // Particles
  23886. /**
  23887. * Gets or sets a boolean indicating if particles are enabled on this scene
  23888. */
  23889. _this.particlesEnabled = true;
  23890. // Sprites
  23891. /**
  23892. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23893. */
  23894. _this.spritesEnabled = true;
  23895. /**
  23896. * All of the sprite managers added to this scene
  23897. * @see http://doc.babylonjs.com/babylon101/sprites
  23898. */
  23899. _this.spriteManagers = new Array();
  23900. // Skeletons
  23901. _this._skeletonsEnabled = true;
  23902. // Lens flares
  23903. /**
  23904. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23905. */
  23906. _this.lensFlaresEnabled = true;
  23907. // Collisions
  23908. /**
  23909. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23910. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23911. */
  23912. _this.collisionsEnabled = true;
  23913. /**
  23914. * Defines the gravity applied to this scene (used only for collisions)
  23915. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23916. */
  23917. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23918. // Postprocesses
  23919. /**
  23920. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23921. */
  23922. _this.postProcessesEnabled = true;
  23923. /**
  23924. * The list of postprocesses added to the scene
  23925. */
  23926. _this.postProcesses = new Array();
  23927. // Customs render targets
  23928. /**
  23929. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23930. */
  23931. _this.renderTargetsEnabled = true;
  23932. /**
  23933. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23934. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23935. */
  23936. _this.dumpNextRenderTargets = false;
  23937. /**
  23938. * The list of user defined render targets added to the scene
  23939. */
  23940. _this.customRenderTargets = new Array();
  23941. /**
  23942. * Gets the list of meshes imported to the scene through SceneLoader
  23943. */
  23944. _this.importedMeshesFiles = new Array();
  23945. // Probes
  23946. /**
  23947. * Gets or sets a boolean indicating if probes are enabled on this scene
  23948. */
  23949. _this.probesEnabled = true;
  23950. /**
  23951. * The list of reflection probes added to the scene
  23952. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23953. */
  23954. _this.reflectionProbes = new Array();
  23955. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23956. // Procedural textures
  23957. /**
  23958. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23959. */
  23960. _this.proceduralTexturesEnabled = true;
  23961. /**
  23962. * The list of procedural textures added to the scene
  23963. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23964. */
  23965. _this.proceduralTextures = new Array();
  23966. /**
  23967. * The list of sound tracks added to the scene
  23968. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23969. */
  23970. _this.soundTracks = new Array();
  23971. _this._audioEnabled = true;
  23972. _this._headphone = false;
  23973. // Performance counters
  23974. _this._totalVertices = new BABYLON.PerfCounter();
  23975. /** @hidden */
  23976. _this._activeIndices = new BABYLON.PerfCounter();
  23977. /** @hidden */
  23978. _this._activeParticles = new BABYLON.PerfCounter();
  23979. /** @hidden */
  23980. _this._activeBones = new BABYLON.PerfCounter();
  23981. _this._animationTime = 0;
  23982. /**
  23983. * Gets or sets a general scale for animation speed
  23984. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23985. */
  23986. _this.animationTimeScale = 1;
  23987. _this._renderId = 0;
  23988. _this._executeWhenReadyTimeoutId = -1;
  23989. _this._intermediateRendering = false;
  23990. _this._viewUpdateFlag = -1;
  23991. _this._projectionUpdateFlag = -1;
  23992. _this._alternateViewUpdateFlag = -1;
  23993. _this._alternateProjectionUpdateFlag = -1;
  23994. /** @hidden */
  23995. _this._toBeDisposed = new BABYLON.SmartArray(256);
  23996. _this._activeRequests = new Array();
  23997. _this._pendingData = new Array();
  23998. _this._isDisposed = false;
  23999. /**
  24000. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24001. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24002. */
  24003. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24004. _this._activeMeshes = new BABYLON.SmartArray(256);
  24005. _this._processedMaterials = new BABYLON.SmartArray(256);
  24006. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24007. /** @hidden */
  24008. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24009. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24010. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24011. /** @hidden */
  24012. _this._activeAnimatables = new Array();
  24013. _this._transformMatrix = BABYLON.Matrix.Zero();
  24014. _this._useAlternateCameraConfiguration = false;
  24015. _this._alternateRendering = false;
  24016. /**
  24017. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24018. * This is useful if there are more lights that the maximum simulteanous authorized
  24019. */
  24020. _this.requireLightSorting = false;
  24021. _this._depthRenderer = {};
  24022. /**
  24023. * Backing store of defined scene components.
  24024. */
  24025. _this._components = [];
  24026. /**
  24027. * Backing store of defined scene components.
  24028. */
  24029. _this._serializableComponents = [];
  24030. /**
  24031. * List of components to register on the next registration step.
  24032. */
  24033. _this._transientComponents = [];
  24034. /**
  24035. * Defines the actions happening before camera updates.
  24036. */
  24037. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24038. /**
  24039. * Defines the actions happening during the per mesh ready checks.
  24040. */
  24041. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24042. /**
  24043. * Defines the actions happening before evaluate active mesh checks.
  24044. */
  24045. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24046. /**
  24047. * Defines the actions happening during the evaluate sub mesh checks.
  24048. */
  24049. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24050. /**
  24051. * Defines the actions happening during the active mesh stage.
  24052. */
  24053. _this._activeMeshStage = BABYLON.Stage.Create();
  24054. /**
  24055. * Defines the actions happening during the per camera render target step.
  24056. */
  24057. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24058. /**
  24059. * Defines the actions happening just before the active camera is drawing.
  24060. */
  24061. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24062. /**
  24063. * Defines the actions happening just before a rendering group is drawing.
  24064. */
  24065. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24066. /**
  24067. * Defines the actions happening just after a rendering group has been drawn.
  24068. */
  24069. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24070. /**
  24071. * Defines the actions happening just after the active camera has been drawn.
  24072. */
  24073. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24074. _this._activeMeshesFrozen = false;
  24075. /** @hidden */
  24076. _this._allowPostProcessClear = true;
  24077. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24078. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24079. _this._engine.scenes.push(_this);
  24080. _this._uid = null;
  24081. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24082. if (BABYLON.PostProcessManager) {
  24083. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24084. }
  24085. if (BABYLON.OutlineRenderer) {
  24086. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24087. }
  24088. if (BABYLON.Tools.IsWindowObjectExist()) {
  24089. _this.attachControl();
  24090. }
  24091. //simplification queue
  24092. if (BABYLON.SimplificationQueue) {
  24093. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24094. }
  24095. //collision coordinator initialization. For now legacy per default.
  24096. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24097. // Uniform Buffer
  24098. _this._createUbo();
  24099. // Default Image processing definition
  24100. if (BABYLON.ImageProcessingConfiguration) {
  24101. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24102. }
  24103. return _this;
  24104. }
  24105. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24106. /** The fog is deactivated */
  24107. get: function () {
  24108. return Scene._FOGMODE_NONE;
  24109. },
  24110. enumerable: true,
  24111. configurable: true
  24112. });
  24113. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24114. /** The fog density is following an exponential function */
  24115. get: function () {
  24116. return Scene._FOGMODE_EXP;
  24117. },
  24118. enumerable: true,
  24119. configurable: true
  24120. });
  24121. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24122. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24123. get: function () {
  24124. return Scene._FOGMODE_EXP2;
  24125. },
  24126. enumerable: true,
  24127. configurable: true
  24128. });
  24129. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24130. /** The fog density is following a linear function. */
  24131. get: function () {
  24132. return Scene._FOGMODE_LINEAR;
  24133. },
  24134. enumerable: true,
  24135. configurable: true
  24136. });
  24137. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24138. /**
  24139. * Texture used in all pbr material as the reflection texture.
  24140. * As in the majority of the scene they are the same (exception for multi room and so on),
  24141. * this is easier to reference from here than from all the materials.
  24142. */
  24143. get: function () {
  24144. return this._environmentTexture;
  24145. },
  24146. /**
  24147. * Texture used in all pbr material as the reflection texture.
  24148. * As in the majority of the scene they are the same (exception for multi room and so on),
  24149. * this is easier to set here than in all the materials.
  24150. */
  24151. set: function (value) {
  24152. if (this._environmentTexture === value) {
  24153. return;
  24154. }
  24155. this._environmentTexture = value;
  24156. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24157. },
  24158. enumerable: true,
  24159. configurable: true
  24160. });
  24161. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24162. /**
  24163. * Default image processing configuration used either in the rendering
  24164. * Forward main pass or through the imageProcessingPostProcess if present.
  24165. * As in the majority of the scene they are the same (exception for multi camera),
  24166. * this is easier to reference from here than from all the materials and post process.
  24167. *
  24168. * No setter as we it is a shared configuration, you can set the values instead.
  24169. */
  24170. get: function () {
  24171. return this._imageProcessingConfiguration;
  24172. },
  24173. enumerable: true,
  24174. configurable: true
  24175. });
  24176. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24177. get: function () {
  24178. return this._forceWireframe;
  24179. },
  24180. /**
  24181. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24182. */
  24183. set: function (value) {
  24184. if (this._forceWireframe === value) {
  24185. return;
  24186. }
  24187. this._forceWireframe = value;
  24188. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24189. },
  24190. enumerable: true,
  24191. configurable: true
  24192. });
  24193. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24194. get: function () {
  24195. return this._forcePointsCloud;
  24196. },
  24197. /**
  24198. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24199. */
  24200. set: function (value) {
  24201. if (this._forcePointsCloud === value) {
  24202. return;
  24203. }
  24204. this._forcePointsCloud = value;
  24205. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24206. },
  24207. enumerable: true,
  24208. configurable: true
  24209. });
  24210. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24211. /**
  24212. * Gets or sets the animation properties override
  24213. */
  24214. get: function () {
  24215. return this._animationPropertiesOverride;
  24216. },
  24217. set: function (value) {
  24218. this._animationPropertiesOverride = value;
  24219. },
  24220. enumerable: true,
  24221. configurable: true
  24222. });
  24223. Object.defineProperty(Scene.prototype, "onDispose", {
  24224. /** Sets a function to be executed when this scene is disposed. */
  24225. set: function (callback) {
  24226. if (this._onDisposeObserver) {
  24227. this.onDisposeObservable.remove(this._onDisposeObserver);
  24228. }
  24229. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24230. },
  24231. enumerable: true,
  24232. configurable: true
  24233. });
  24234. Object.defineProperty(Scene.prototype, "beforeRender", {
  24235. /** Sets a function to be executed before rendering this scene */
  24236. set: function (callback) {
  24237. if (this._onBeforeRenderObserver) {
  24238. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24239. }
  24240. if (callback) {
  24241. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24242. }
  24243. },
  24244. enumerable: true,
  24245. configurable: true
  24246. });
  24247. Object.defineProperty(Scene.prototype, "afterRender", {
  24248. /** Sets a function to be executed after rendering this scene */
  24249. set: function (callback) {
  24250. if (this._onAfterRenderObserver) {
  24251. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24252. }
  24253. if (callback) {
  24254. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24255. }
  24256. },
  24257. enumerable: true,
  24258. configurable: true
  24259. });
  24260. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24261. /** Sets a function to be executed before rendering a camera*/
  24262. set: function (callback) {
  24263. if (this._onBeforeCameraRenderObserver) {
  24264. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24265. }
  24266. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24267. },
  24268. enumerable: true,
  24269. configurable: true
  24270. });
  24271. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24272. /** Sets a function to be executed after rendering a camera*/
  24273. set: function (callback) {
  24274. if (this._onAfterCameraRenderObserver) {
  24275. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24276. }
  24277. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24278. },
  24279. enumerable: true,
  24280. configurable: true
  24281. });
  24282. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24283. /**
  24284. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24285. */
  24286. get: function () {
  24287. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24288. },
  24289. enumerable: true,
  24290. configurable: true
  24291. });
  24292. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24293. get: function () {
  24294. return this._useRightHandedSystem;
  24295. },
  24296. /**
  24297. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24298. */
  24299. set: function (value) {
  24300. if (this._useRightHandedSystem === value) {
  24301. return;
  24302. }
  24303. this._useRightHandedSystem = value;
  24304. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24305. },
  24306. enumerable: true,
  24307. configurable: true
  24308. });
  24309. /**
  24310. * Sets the step Id used by deterministic lock step
  24311. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24312. * @param newStepId defines the step Id
  24313. */
  24314. Scene.prototype.setStepId = function (newStepId) {
  24315. this._currentStepId = newStepId;
  24316. };
  24317. ;
  24318. /**
  24319. * Gets the step Id used by deterministic lock step
  24320. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24321. * @returns the step Id
  24322. */
  24323. Scene.prototype.getStepId = function () {
  24324. return this._currentStepId;
  24325. };
  24326. ;
  24327. /**
  24328. * Gets the internal step used by deterministic lock step
  24329. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24330. * @returns the internal step
  24331. */
  24332. Scene.prototype.getInternalStep = function () {
  24333. return this._currentInternalStep;
  24334. };
  24335. ;
  24336. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24337. get: function () {
  24338. return this._fogEnabled;
  24339. },
  24340. /**
  24341. * Gets or sets a boolean indicating if fog is enabled on this scene
  24342. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24343. */
  24344. set: function (value) {
  24345. if (this._fogEnabled === value) {
  24346. return;
  24347. }
  24348. this._fogEnabled = value;
  24349. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24350. },
  24351. enumerable: true,
  24352. configurable: true
  24353. });
  24354. Object.defineProperty(Scene.prototype, "fogMode", {
  24355. get: function () {
  24356. return this._fogMode;
  24357. },
  24358. /**
  24359. * Gets or sets the fog mode to use
  24360. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24361. */
  24362. set: function (value) {
  24363. if (this._fogMode === value) {
  24364. return;
  24365. }
  24366. this._fogMode = value;
  24367. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24368. },
  24369. enumerable: true,
  24370. configurable: true
  24371. });
  24372. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24373. get: function () {
  24374. return this._shadowsEnabled;
  24375. },
  24376. /**
  24377. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24378. */
  24379. set: function (value) {
  24380. if (this._shadowsEnabled === value) {
  24381. return;
  24382. }
  24383. this._shadowsEnabled = value;
  24384. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24385. },
  24386. enumerable: true,
  24387. configurable: true
  24388. });
  24389. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24390. get: function () {
  24391. return this._lightsEnabled;
  24392. },
  24393. /**
  24394. * Gets or sets a boolean indicating if lights are enabled on this scene
  24395. */
  24396. set: function (value) {
  24397. if (this._lightsEnabled === value) {
  24398. return;
  24399. }
  24400. this._lightsEnabled = value;
  24401. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24402. },
  24403. enumerable: true,
  24404. configurable: true
  24405. });
  24406. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24407. /** The default material used on meshes when no material is affected */
  24408. get: function () {
  24409. if (!this._defaultMaterial) {
  24410. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24411. }
  24412. return this._defaultMaterial;
  24413. },
  24414. /** The default material used on meshes when no material is affected */
  24415. set: function (value) {
  24416. this._defaultMaterial = value;
  24417. },
  24418. enumerable: true,
  24419. configurable: true
  24420. });
  24421. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24422. get: function () {
  24423. return this._texturesEnabled;
  24424. },
  24425. /**
  24426. * Gets or sets a boolean indicating if textures are enabled on this scene
  24427. */
  24428. set: function (value) {
  24429. if (this._texturesEnabled === value) {
  24430. return;
  24431. }
  24432. this._texturesEnabled = value;
  24433. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24434. },
  24435. enumerable: true,
  24436. configurable: true
  24437. });
  24438. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24439. get: function () {
  24440. return this._skeletonsEnabled;
  24441. },
  24442. /**
  24443. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24444. */
  24445. set: function (value) {
  24446. if (this._skeletonsEnabled === value) {
  24447. return;
  24448. }
  24449. this._skeletonsEnabled = value;
  24450. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24451. },
  24452. enumerable: true,
  24453. configurable: true
  24454. });
  24455. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24456. /**
  24457. * Gets the postprocess render pipeline manager
  24458. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24459. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24460. */
  24461. get: function () {
  24462. if (!this._postProcessRenderPipelineManager) {
  24463. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24464. }
  24465. return this._postProcessRenderPipelineManager;
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24471. /**
  24472. * Gets the main soundtrack associated with the scene
  24473. */
  24474. get: function () {
  24475. if (!this._mainSoundTrack) {
  24476. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24477. }
  24478. return this._mainSoundTrack;
  24479. },
  24480. enumerable: true,
  24481. configurable: true
  24482. });
  24483. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24484. /** @hidden */
  24485. get: function () {
  24486. return this._alternateRendering;
  24487. },
  24488. enumerable: true,
  24489. configurable: true
  24490. });
  24491. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24492. /**
  24493. * Gets the list of frustum planes (built from the active camera)
  24494. */
  24495. get: function () {
  24496. return this._frustumPlanes;
  24497. },
  24498. enumerable: true,
  24499. configurable: true
  24500. });
  24501. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24502. /**
  24503. * Gets the current geometry buffer associated to the scene.
  24504. */
  24505. get: function () {
  24506. return this._geometryBufferRenderer;
  24507. },
  24508. /**
  24509. * Sets the current geometry buffer for the scene.
  24510. */
  24511. set: function (geometryBufferRenderer) {
  24512. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24513. this._geometryBufferRenderer = geometryBufferRenderer;
  24514. }
  24515. },
  24516. enumerable: true,
  24517. configurable: true
  24518. });
  24519. /**
  24520. * Registers the transient components if needed.
  24521. */
  24522. Scene.prototype._registerTransientComponents = function () {
  24523. // Register components that have been associated lately to the scene.
  24524. if (this._transientComponents.length > 0) {
  24525. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24526. var component = _a[_i];
  24527. component.register();
  24528. }
  24529. this._transientComponents = [];
  24530. }
  24531. };
  24532. /**
  24533. * Add a component to the scene.
  24534. * Note that the ccomponent could be registered on th next frame if this is called after
  24535. * the register component stage.
  24536. * @param component Defines the component to add to the scene
  24537. */
  24538. Scene.prototype._addComponent = function (component) {
  24539. this._components.push(component);
  24540. this._transientComponents.push(component);
  24541. var serializableComponent = component;
  24542. if (serializableComponent.addFromContainer) {
  24543. this._serializableComponents.push(serializableComponent);
  24544. }
  24545. };
  24546. /**
  24547. * Gets a component from the scene.
  24548. * @param name defines the name of the component to retrieve
  24549. * @returns the component or null if not present
  24550. */
  24551. Scene.prototype._getComponent = function (name) {
  24552. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24553. var component = _a[_i];
  24554. if (component.name === name) {
  24555. return component;
  24556. }
  24557. }
  24558. return null;
  24559. };
  24560. Object.defineProperty(Scene.prototype, "debugLayer", {
  24561. /**
  24562. * Gets the debug layer (aka Inspector) associated with the scene
  24563. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24564. */
  24565. get: function () {
  24566. if (!this._debugLayer) {
  24567. this._debugLayer = new BABYLON.DebugLayer(this);
  24568. }
  24569. return this._debugLayer;
  24570. },
  24571. enumerable: true,
  24572. configurable: true
  24573. });
  24574. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24575. /**
  24576. * Gets a boolean indicating if collisions are processed on a web worker
  24577. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24578. */
  24579. get: function () {
  24580. return this._workerCollisions;
  24581. },
  24582. set: function (enabled) {
  24583. if (!BABYLON.CollisionCoordinatorLegacy) {
  24584. return;
  24585. }
  24586. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24587. this._workerCollisions = enabled;
  24588. if (this.collisionCoordinator) {
  24589. this.collisionCoordinator.destroy();
  24590. }
  24591. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24592. this.collisionCoordinator.init(this);
  24593. },
  24594. enumerable: true,
  24595. configurable: true
  24596. });
  24597. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24598. /**
  24599. * Gets the octree used to boost mesh selection (picking)
  24600. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24601. */
  24602. get: function () {
  24603. return this._selectionOctree;
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24609. /**
  24610. * Gets the mesh that is currently under the pointer
  24611. */
  24612. get: function () {
  24613. return this._pointerOverMesh;
  24614. },
  24615. enumerable: true,
  24616. configurable: true
  24617. });
  24618. Object.defineProperty(Scene.prototype, "pointerX", {
  24619. /**
  24620. * Gets the current on-screen X position of the pointer
  24621. */
  24622. get: function () {
  24623. return this._pointerX;
  24624. },
  24625. enumerable: true,
  24626. configurable: true
  24627. });
  24628. Object.defineProperty(Scene.prototype, "pointerY", {
  24629. /**
  24630. * Gets the current on-screen Y position of the pointer
  24631. */
  24632. get: function () {
  24633. return this._pointerY;
  24634. },
  24635. enumerable: true,
  24636. configurable: true
  24637. });
  24638. /**
  24639. * Gets the cached material (ie. the latest rendered one)
  24640. * @returns the cached material
  24641. */
  24642. Scene.prototype.getCachedMaterial = function () {
  24643. return this._cachedMaterial;
  24644. };
  24645. /**
  24646. * Gets the cached effect (ie. the latest rendered one)
  24647. * @returns the cached effect
  24648. */
  24649. Scene.prototype.getCachedEffect = function () {
  24650. return this._cachedEffect;
  24651. };
  24652. /**
  24653. * Gets the cached visibility state (ie. the latest rendered one)
  24654. * @returns the cached visibility state
  24655. */
  24656. Scene.prototype.getCachedVisibility = function () {
  24657. return this._cachedVisibility;
  24658. };
  24659. /**
  24660. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24661. * @param material defines the current material
  24662. * @param effect defines the current effect
  24663. * @param visibility defines the current visibility state
  24664. * @returns true if one parameter is not cached
  24665. */
  24666. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24667. if (visibility === void 0) { visibility = 1; }
  24668. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24669. };
  24670. /**
  24671. * Gets the outline renderer associated with the scene
  24672. * @returns a OutlineRenderer
  24673. */
  24674. Scene.prototype.getOutlineRenderer = function () {
  24675. return this._outlineRenderer;
  24676. };
  24677. /**
  24678. * Gets the engine associated with the scene
  24679. * @returns an Engine
  24680. */
  24681. Scene.prototype.getEngine = function () {
  24682. return this._engine;
  24683. };
  24684. /**
  24685. * Gets the total number of vertices rendered per frame
  24686. * @returns the total number of vertices rendered per frame
  24687. */
  24688. Scene.prototype.getTotalVertices = function () {
  24689. return this._totalVertices.current;
  24690. };
  24691. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24692. /**
  24693. * Gets the performance counter for total vertices
  24694. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24695. */
  24696. get: function () {
  24697. return this._totalVertices;
  24698. },
  24699. enumerable: true,
  24700. configurable: true
  24701. });
  24702. /**
  24703. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24704. * @returns the total number of active indices rendered per frame
  24705. */
  24706. Scene.prototype.getActiveIndices = function () {
  24707. return this._activeIndices.current;
  24708. };
  24709. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24710. /**
  24711. * Gets the performance counter for active indices
  24712. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24713. */
  24714. get: function () {
  24715. return this._activeIndices;
  24716. },
  24717. enumerable: true,
  24718. configurable: true
  24719. });
  24720. /**
  24721. * Gets the total number of active particles rendered per frame
  24722. * @returns the total number of active particles rendered per frame
  24723. */
  24724. Scene.prototype.getActiveParticles = function () {
  24725. return this._activeParticles.current;
  24726. };
  24727. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24728. /**
  24729. * Gets the performance counter for active particles
  24730. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24731. */
  24732. get: function () {
  24733. return this._activeParticles;
  24734. },
  24735. enumerable: true,
  24736. configurable: true
  24737. });
  24738. /**
  24739. * Gets the total number of active bones rendered per frame
  24740. * @returns the total number of active bones rendered per frame
  24741. */
  24742. Scene.prototype.getActiveBones = function () {
  24743. return this._activeBones.current;
  24744. };
  24745. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24746. /**
  24747. * Gets the performance counter for active bones
  24748. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24749. */
  24750. get: function () {
  24751. return this._activeBones;
  24752. },
  24753. enumerable: true,
  24754. configurable: true
  24755. });
  24756. /** @hidden */
  24757. Scene.prototype.getInterFramePerfCounter = function () {
  24758. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24759. return 0;
  24760. };
  24761. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24762. /** @hidden */
  24763. get: function () {
  24764. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24765. return null;
  24766. },
  24767. enumerable: true,
  24768. configurable: true
  24769. });
  24770. /** @hidden */
  24771. Scene.prototype.getLastFrameDuration = function () {
  24772. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24773. return 0;
  24774. };
  24775. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24776. /** @hidden */
  24777. get: function () {
  24778. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24779. return null;
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. /** @hidden */
  24785. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24786. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24787. return 0;
  24788. };
  24789. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24790. /** @hidden */
  24791. get: function () {
  24792. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24793. return null;
  24794. },
  24795. enumerable: true,
  24796. configurable: true
  24797. });
  24798. /**
  24799. * Gets the array of active meshes
  24800. * @returns an array of AbstractMesh
  24801. */
  24802. Scene.prototype.getActiveMeshes = function () {
  24803. return this._activeMeshes;
  24804. };
  24805. /** @hidden */
  24806. Scene.prototype.getRenderTargetsDuration = function () {
  24807. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24808. return 0;
  24809. };
  24810. /** @hidden */
  24811. Scene.prototype.getRenderDuration = function () {
  24812. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24813. return 0;
  24814. };
  24815. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24816. /** @hidden */
  24817. get: function () {
  24818. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24819. return null;
  24820. },
  24821. enumerable: true,
  24822. configurable: true
  24823. });
  24824. /** @hidden */
  24825. Scene.prototype.getParticlesDuration = function () {
  24826. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24827. return 0;
  24828. };
  24829. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24830. /** @hidden */
  24831. get: function () {
  24832. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24833. return null;
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. /** @hidden */
  24839. Scene.prototype.getSpritesDuration = function () {
  24840. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24841. return 0;
  24842. };
  24843. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24844. /** @hidden */
  24845. get: function () {
  24846. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24847. return null;
  24848. },
  24849. enumerable: true,
  24850. configurable: true
  24851. });
  24852. /**
  24853. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24854. * @returns a number
  24855. */
  24856. Scene.prototype.getAnimationRatio = function () {
  24857. return this._animationRatio !== undefined ? this._animationRatio : 1;
  24858. };
  24859. /**
  24860. * Gets an unique Id for the current frame
  24861. * @returns a number
  24862. */
  24863. Scene.prototype.getRenderId = function () {
  24864. return this._renderId;
  24865. };
  24866. /** Call this function if you want to manually increment the render Id*/
  24867. Scene.prototype.incrementRenderId = function () {
  24868. this._renderId++;
  24869. };
  24870. Scene.prototype._updatePointerPosition = function (evt) {
  24871. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24872. if (!canvasRect) {
  24873. return;
  24874. }
  24875. this._pointerX = evt.clientX - canvasRect.left;
  24876. this._pointerY = evt.clientY - canvasRect.top;
  24877. this._unTranslatedPointerX = this._pointerX;
  24878. this._unTranslatedPointerY = this._pointerY;
  24879. };
  24880. Scene.prototype._createUbo = function () {
  24881. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24882. this._sceneUbo.addUniform("viewProjection", 16);
  24883. this._sceneUbo.addUniform("view", 16);
  24884. };
  24885. Scene.prototype._createAlternateUbo = function () {
  24886. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24887. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24888. this._alternateSceneUbo.addUniform("view", 16);
  24889. };
  24890. // Pointers handling
  24891. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24892. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24893. if (result) {
  24894. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24895. }
  24896. return result;
  24897. };
  24898. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24899. if (pointerInfo.pickInfo) {
  24900. if (!pointerInfo.pickInfo.ray) {
  24901. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24902. }
  24903. }
  24904. };
  24905. /**
  24906. * Use this method to simulate a pointer move on a mesh
  24907. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24908. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24909. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24910. * @returns the current scene
  24911. */
  24912. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24913. var evt = new PointerEvent("pointermove", pointerEventInit);
  24914. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24915. return this;
  24916. }
  24917. return this._processPointerMove(pickResult, evt);
  24918. };
  24919. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24920. var canvas = this._engine.getRenderingCanvas();
  24921. if (!canvas) {
  24922. return this;
  24923. }
  24924. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24925. this.setPointerOverSprite(null);
  24926. this.setPointerOverMesh(pickResult.pickedMesh);
  24927. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24928. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24929. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24930. }
  24931. else {
  24932. canvas.style.cursor = this.hoverCursor;
  24933. }
  24934. }
  24935. else {
  24936. canvas.style.cursor = this.defaultCursor;
  24937. }
  24938. }
  24939. else {
  24940. this.setPointerOverMesh(null);
  24941. // Sprites
  24942. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24943. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24944. this.setPointerOverSprite(pickResult.pickedSprite);
  24945. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24946. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24947. }
  24948. else {
  24949. canvas.style.cursor = this.hoverCursor;
  24950. }
  24951. }
  24952. else {
  24953. this.setPointerOverSprite(null);
  24954. // Restore pointer
  24955. canvas.style.cursor = this.defaultCursor;
  24956. }
  24957. }
  24958. if (pickResult) {
  24959. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24960. if (this.onPointerMove) {
  24961. this.onPointerMove(evt, pickResult, type);
  24962. }
  24963. if (this.onPointerObservable.hasObservers()) {
  24964. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24965. this._setRayOnPointerInfo(pi);
  24966. this.onPointerObservable.notifyObservers(pi, type);
  24967. }
  24968. }
  24969. return this;
  24970. };
  24971. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  24972. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  24973. if (pickResult) {
  24974. pi.ray = pickResult.ray;
  24975. }
  24976. this.onPrePointerObservable.notifyObservers(pi, type);
  24977. if (pi.skipOnPointerObservable) {
  24978. return true;
  24979. }
  24980. else {
  24981. return false;
  24982. }
  24983. };
  24984. /**
  24985. * Use this method to simulate a pointer down on a mesh
  24986. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24987. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24988. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24989. * @returns the current scene
  24990. */
  24991. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24992. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24993. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  24994. return this;
  24995. }
  24996. return this._processPointerDown(pickResult, evt);
  24997. };
  24998. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24999. var _this = this;
  25000. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25001. this._pickedDownMesh = pickResult.pickedMesh;
  25002. var actionManager = pickResult.pickedMesh.actionManager;
  25003. if (actionManager) {
  25004. if (actionManager.hasPickTriggers) {
  25005. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25006. switch (evt.button) {
  25007. case 0:
  25008. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25009. break;
  25010. case 1:
  25011. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25012. break;
  25013. case 2:
  25014. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25015. break;
  25016. }
  25017. }
  25018. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25019. window.setTimeout(function () {
  25020. 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);
  25021. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25022. if (_this._totalPointersPressed !== 0 &&
  25023. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25024. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25025. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25026. _this._startingPointerTime = 0;
  25027. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25028. }
  25029. }
  25030. }, Scene.LongPressDelay);
  25031. }
  25032. }
  25033. }
  25034. if (pickResult) {
  25035. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25036. if (this.onPointerDown) {
  25037. this.onPointerDown(evt, pickResult, type);
  25038. }
  25039. if (this.onPointerObservable.hasObservers()) {
  25040. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25041. this._setRayOnPointerInfo(pi);
  25042. this.onPointerObservable.notifyObservers(pi, type);
  25043. }
  25044. }
  25045. return this;
  25046. };
  25047. /**
  25048. * Use this method to simulate a pointer up on a mesh
  25049. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25050. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25051. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25052. * @returns the current scene
  25053. */
  25054. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25055. var evt = new PointerEvent("pointerup", pointerEventInit);
  25056. var clickInfo = new ClickInfo();
  25057. clickInfo.singleClick = true;
  25058. clickInfo.ignore = true;
  25059. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25060. return this;
  25061. }
  25062. return this._processPointerUp(pickResult, evt, clickInfo);
  25063. };
  25064. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25065. if (pickResult && pickResult && pickResult.pickedMesh) {
  25066. this._pickedUpMesh = pickResult.pickedMesh;
  25067. if (this._pickedDownMesh === this._pickedUpMesh) {
  25068. if (this.onPointerPick) {
  25069. this.onPointerPick(evt, pickResult);
  25070. }
  25071. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25072. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25073. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25074. this._setRayOnPointerInfo(pi);
  25075. this.onPointerObservable.notifyObservers(pi, type_1);
  25076. }
  25077. }
  25078. if (pickResult.pickedMesh.actionManager) {
  25079. if (clickInfo.ignore) {
  25080. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25081. }
  25082. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25083. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25084. }
  25085. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25086. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25087. }
  25088. }
  25089. }
  25090. if (this._pickedDownMesh &&
  25091. this._pickedDownMesh.actionManager &&
  25092. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25093. this._pickedDownMesh !== this._pickedUpMesh) {
  25094. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25095. }
  25096. var type = BABYLON.PointerEventTypes.POINTERUP;
  25097. if (this.onPointerObservable.hasObservers()) {
  25098. if (!clickInfo.ignore) {
  25099. if (!clickInfo.hasSwiped) {
  25100. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25101. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25102. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25103. this._setRayOnPointerInfo(pi);
  25104. this.onPointerObservable.notifyObservers(pi, type_2);
  25105. }
  25106. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25107. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25108. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25109. this._setRayOnPointerInfo(pi);
  25110. this.onPointerObservable.notifyObservers(pi, type_3);
  25111. }
  25112. }
  25113. }
  25114. else {
  25115. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25116. this._setRayOnPointerInfo(pi);
  25117. this.onPointerObservable.notifyObservers(pi, type);
  25118. }
  25119. }
  25120. if (this.onPointerUp) {
  25121. this.onPointerUp(evt, pickResult, type);
  25122. }
  25123. return this;
  25124. };
  25125. /**
  25126. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25127. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25128. * @returns true if the pointer was captured
  25129. */
  25130. Scene.prototype.isPointerCaptured = function (pointerId) {
  25131. if (pointerId === void 0) { pointerId = 0; }
  25132. return this._pointerCaptures[pointerId];
  25133. };
  25134. /**
  25135. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25136. * @param attachUp defines if you want to attach events to pointerup
  25137. * @param attachDown defines if you want to attach events to pointerdown
  25138. * @param attachMove defines if you want to attach events to pointermove
  25139. */
  25140. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25141. var _this = this;
  25142. if (attachUp === void 0) { attachUp = true; }
  25143. if (attachDown === void 0) { attachDown = true; }
  25144. if (attachMove === void 0) { attachMove = true; }
  25145. this._initActionManager = function (act, clickInfo) {
  25146. if (!_this._meshPickProceed) {
  25147. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25148. _this._currentPickResult = pickResult;
  25149. if (pickResult) {
  25150. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25151. }
  25152. _this._meshPickProceed = true;
  25153. }
  25154. return act;
  25155. };
  25156. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25157. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25158. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25159. btn !== _this._previousButtonPressed) {
  25160. _this._doubleClickOccured = false;
  25161. clickInfo.singleClick = true;
  25162. clickInfo.ignore = false;
  25163. cb(clickInfo, _this._currentPickResult);
  25164. }
  25165. };
  25166. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25167. var clickInfo = new ClickInfo();
  25168. _this._currentPickResult = null;
  25169. var act = null;
  25170. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25171. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25172. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25173. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25174. act = _this._initActionManager(act, clickInfo);
  25175. if (act)
  25176. checkPicking = act.hasPickTriggers;
  25177. }
  25178. if (checkPicking) {
  25179. var btn = evt.button;
  25180. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25181. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25182. if (!clickInfo.hasSwiped) {
  25183. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25184. if (!checkSingleClickImmediately) {
  25185. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25186. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25187. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25188. act = _this._initActionManager(act, clickInfo);
  25189. if (act)
  25190. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25191. }
  25192. }
  25193. if (checkSingleClickImmediately) {
  25194. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25195. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25196. btn !== _this._previousButtonPressed) {
  25197. clickInfo.singleClick = true;
  25198. cb(clickInfo, _this._currentPickResult);
  25199. }
  25200. }
  25201. // at least one double click is required to be check and exclusive double click is enabled
  25202. else {
  25203. // wait that no double click has been raised during the double click delay
  25204. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25205. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25206. }
  25207. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25208. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25209. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25210. act = _this._initActionManager(act, clickInfo);
  25211. if (act)
  25212. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25213. }
  25214. if (checkDoubleClick) {
  25215. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25216. if (btn === _this._previousButtonPressed &&
  25217. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25218. !_this._doubleClickOccured) {
  25219. // pointer has not moved for 2 clicks, it's a double click
  25220. if (!clickInfo.hasSwiped &&
  25221. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25222. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25223. _this._previousStartingPointerTime = 0;
  25224. _this._doubleClickOccured = true;
  25225. clickInfo.doubleClick = true;
  25226. clickInfo.ignore = false;
  25227. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25228. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25229. }
  25230. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25231. cb(clickInfo, _this._currentPickResult);
  25232. }
  25233. // if the two successive clicks are too far, it's just two simple clicks
  25234. else {
  25235. _this._doubleClickOccured = false;
  25236. _this._previousStartingPointerTime = _this._startingPointerTime;
  25237. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25238. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25239. _this._previousButtonPressed = btn;
  25240. if (Scene.ExclusiveDoubleClickMode) {
  25241. if (_this._previousDelayedSimpleClickTimeout) {
  25242. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25243. }
  25244. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25245. cb(clickInfo, _this._previousPickResult);
  25246. }
  25247. else {
  25248. cb(clickInfo, _this._currentPickResult);
  25249. }
  25250. }
  25251. }
  25252. // just the first click of the double has been raised
  25253. else {
  25254. _this._doubleClickOccured = false;
  25255. _this._previousStartingPointerTime = _this._startingPointerTime;
  25256. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25257. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25258. _this._previousButtonPressed = btn;
  25259. }
  25260. }
  25261. }
  25262. }
  25263. clickInfo.ignore = true;
  25264. cb(clickInfo, _this._currentPickResult);
  25265. };
  25266. this._spritePredicate = function (sprite) {
  25267. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25268. };
  25269. this._onPointerMove = function (evt) {
  25270. _this._updatePointerPosition(evt);
  25271. // PreObservable support
  25272. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25273. return;
  25274. }
  25275. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25276. return;
  25277. }
  25278. if (!_this.pointerMovePredicate) {
  25279. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25280. }
  25281. // Meshes
  25282. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25283. _this._processPointerMove(pickResult, evt);
  25284. };
  25285. this._onPointerDown = function (evt) {
  25286. _this._totalPointersPressed++;
  25287. _this._pickedDownMesh = null;
  25288. _this._meshPickProceed = false;
  25289. _this._updatePointerPosition(evt);
  25290. if (_this.preventDefaultOnPointerDown && canvas) {
  25291. evt.preventDefault();
  25292. canvas.focus();
  25293. }
  25294. // PreObservable support
  25295. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25296. return;
  25297. }
  25298. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25299. return;
  25300. }
  25301. _this._pointerCaptures[evt.pointerId] = true;
  25302. _this._startingPointerPosition.x = _this._pointerX;
  25303. _this._startingPointerPosition.y = _this._pointerY;
  25304. _this._startingPointerTime = Date.now();
  25305. if (!_this.pointerDownPredicate) {
  25306. _this.pointerDownPredicate = function (mesh) {
  25307. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25308. };
  25309. }
  25310. // Meshes
  25311. _this._pickedDownMesh = null;
  25312. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25313. _this._processPointerDown(pickResult, evt);
  25314. // Sprites
  25315. _this._pickedDownSprite = null;
  25316. if (_this.spriteManagers.length > 0) {
  25317. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25318. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25319. if (pickResult.pickedSprite.actionManager) {
  25320. _this._pickedDownSprite = pickResult.pickedSprite;
  25321. switch (evt.button) {
  25322. case 0:
  25323. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25324. break;
  25325. case 1:
  25326. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25327. break;
  25328. case 2:
  25329. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25330. break;
  25331. }
  25332. if (pickResult.pickedSprite.actionManager) {
  25333. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25334. }
  25335. }
  25336. }
  25337. }
  25338. };
  25339. this._onPointerUp = function (evt) {
  25340. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25341. return; // So we need to test it the pointer down was pressed before.
  25342. }
  25343. _this._totalPointersPressed--;
  25344. _this._pickedUpMesh = null;
  25345. _this._meshPickProceed = false;
  25346. _this._updatePointerPosition(evt);
  25347. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25348. // PreObservable support
  25349. if (_this.onPrePointerObservable.hasObservers()) {
  25350. if (!clickInfo.ignore) {
  25351. if (!clickInfo.hasSwiped) {
  25352. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25353. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25354. return;
  25355. }
  25356. }
  25357. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25358. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25359. return;
  25360. }
  25361. }
  25362. }
  25363. }
  25364. else {
  25365. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25366. return;
  25367. }
  25368. }
  25369. }
  25370. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25371. return;
  25372. }
  25373. _this._pointerCaptures[evt.pointerId] = false;
  25374. if (!_this.pointerUpPredicate) {
  25375. _this.pointerUpPredicate = function (mesh) {
  25376. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25377. };
  25378. }
  25379. // Meshes
  25380. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25381. _this._initActionManager(null, clickInfo);
  25382. }
  25383. if (!pickResult) {
  25384. pickResult = _this._currentPickResult;
  25385. }
  25386. _this._processPointerUp(pickResult, evt, clickInfo);
  25387. // Sprites
  25388. if (!clickInfo.ignore) {
  25389. if (_this.spriteManagers.length > 0) {
  25390. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25391. if (spritePickResult) {
  25392. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25393. if (spritePickResult.pickedSprite.actionManager) {
  25394. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25395. if (spritePickResult.pickedSprite.actionManager) {
  25396. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25397. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25398. }
  25399. }
  25400. }
  25401. }
  25402. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25403. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25404. }
  25405. }
  25406. }
  25407. }
  25408. _this._previousPickResult = _this._currentPickResult;
  25409. });
  25410. };
  25411. this._onKeyDown = function (evt) {
  25412. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25413. if (_this.onPreKeyboardObservable.hasObservers()) {
  25414. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25415. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25416. if (pi.skipOnPointerObservable) {
  25417. return;
  25418. }
  25419. }
  25420. if (_this.onKeyboardObservable.hasObservers()) {
  25421. var pi = new BABYLON.KeyboardInfo(type, evt);
  25422. _this.onKeyboardObservable.notifyObservers(pi, type);
  25423. }
  25424. if (_this.actionManager) {
  25425. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25426. }
  25427. };
  25428. this._onKeyUp = function (evt) {
  25429. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25430. if (_this.onPreKeyboardObservable.hasObservers()) {
  25431. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25432. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25433. if (pi.skipOnPointerObservable) {
  25434. return;
  25435. }
  25436. }
  25437. if (_this.onKeyboardObservable.hasObservers()) {
  25438. var pi = new BABYLON.KeyboardInfo(type, evt);
  25439. _this.onKeyboardObservable.notifyObservers(pi, type);
  25440. }
  25441. if (_this.actionManager) {
  25442. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25443. }
  25444. };
  25445. var engine = this.getEngine();
  25446. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25447. if (!canvas) {
  25448. return;
  25449. }
  25450. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25451. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25452. });
  25453. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25454. if (!canvas) {
  25455. return;
  25456. }
  25457. canvas.removeEventListener("keydown", _this._onKeyDown);
  25458. canvas.removeEventListener("keyup", _this._onKeyUp);
  25459. });
  25460. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25461. var canvas = this._engine.getRenderingCanvas();
  25462. if (!canvas) {
  25463. return;
  25464. }
  25465. if (attachMove) {
  25466. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25467. // Wheel
  25468. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25469. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25470. }
  25471. if (attachDown) {
  25472. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25473. }
  25474. if (attachUp) {
  25475. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25476. }
  25477. canvas.tabIndex = 1;
  25478. };
  25479. /** Detaches all event handlers*/
  25480. Scene.prototype.detachControl = function () {
  25481. var engine = this.getEngine();
  25482. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25483. var canvas = engine.getRenderingCanvas();
  25484. if (!canvas) {
  25485. return;
  25486. }
  25487. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25488. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25489. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25490. if (this._onCanvasBlurObserver) {
  25491. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25492. }
  25493. if (this._onCanvasFocusObserver) {
  25494. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25495. }
  25496. // Wheel
  25497. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25498. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25499. // Keyboard
  25500. canvas.removeEventListener("keydown", this._onKeyDown);
  25501. canvas.removeEventListener("keyup", this._onKeyUp);
  25502. // Observables
  25503. this.onKeyboardObservable.clear();
  25504. this.onPreKeyboardObservable.clear();
  25505. this.onPointerObservable.clear();
  25506. this.onPrePointerObservable.clear();
  25507. };
  25508. /**
  25509. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25510. * Delay loaded resources are not taking in account
  25511. * @return true if all required resources are ready
  25512. */
  25513. Scene.prototype.isReady = function () {
  25514. if (this._isDisposed) {
  25515. return false;
  25516. }
  25517. if (this._pendingData.length > 0) {
  25518. return false;
  25519. }
  25520. var index;
  25521. var engine = this.getEngine();
  25522. // Geometries
  25523. for (index = 0; index < this.geometries.length; index++) {
  25524. var geometry = this.geometries[index];
  25525. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25526. return false;
  25527. }
  25528. }
  25529. // Meshes
  25530. for (index = 0; index < this.meshes.length; index++) {
  25531. var mesh = this.meshes[index];
  25532. if (!mesh.isEnabled()) {
  25533. continue;
  25534. }
  25535. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25536. continue;
  25537. }
  25538. if (!mesh.isReady(true)) {
  25539. return false;
  25540. }
  25541. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25542. // Is Ready For Mesh
  25543. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25544. var step = _a[_i];
  25545. if (!step.action(mesh, hardwareInstancedRendering)) {
  25546. return false;
  25547. }
  25548. }
  25549. }
  25550. // Post-processes
  25551. if (this.activeCameras && this.activeCameras.length > 0) {
  25552. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25553. var camera = _c[_b];
  25554. if (!camera.isReady(true)) {
  25555. return false;
  25556. }
  25557. }
  25558. }
  25559. else if (this.activeCamera) {
  25560. if (!this.activeCamera.isReady(true)) {
  25561. return false;
  25562. }
  25563. }
  25564. // Particles
  25565. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25566. var particleSystem = _e[_d];
  25567. if (!particleSystem.isReady()) {
  25568. return false;
  25569. }
  25570. }
  25571. return true;
  25572. };
  25573. /** Resets all cached information relative to material (including effect and visibility) */
  25574. Scene.prototype.resetCachedMaterial = function () {
  25575. this._cachedMaterial = null;
  25576. this._cachedEffect = null;
  25577. this._cachedVisibility = null;
  25578. };
  25579. /**
  25580. * Registers a function to be called before every frame render
  25581. * @param func defines the function to register
  25582. */
  25583. Scene.prototype.registerBeforeRender = function (func) {
  25584. this.onBeforeRenderObservable.add(func);
  25585. };
  25586. /**
  25587. * Unregisters a function called before every frame render
  25588. * @param func defines the function to unregister
  25589. */
  25590. Scene.prototype.unregisterBeforeRender = function (func) {
  25591. this.onBeforeRenderObservable.removeCallback(func);
  25592. };
  25593. /**
  25594. * Registers a function to be called after every frame render
  25595. * @param func defines the function to register
  25596. */
  25597. Scene.prototype.registerAfterRender = function (func) {
  25598. this.onAfterRenderObservable.add(func);
  25599. };
  25600. /**
  25601. * Unregisters a function called after every frame render
  25602. * @param func defines the function to unregister
  25603. */
  25604. Scene.prototype.unregisterAfterRender = function (func) {
  25605. this.onAfterRenderObservable.removeCallback(func);
  25606. };
  25607. Scene.prototype._executeOnceBeforeRender = function (func) {
  25608. var _this = this;
  25609. var execFunc = function () {
  25610. func();
  25611. setTimeout(function () {
  25612. _this.unregisterBeforeRender(execFunc);
  25613. });
  25614. };
  25615. this.registerBeforeRender(execFunc);
  25616. };
  25617. /**
  25618. * The provided function will run before render once and will be disposed afterwards.
  25619. * A timeout delay can be provided so that the function will be executed in N ms.
  25620. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25621. * @param func The function to be executed.
  25622. * @param timeout optional delay in ms
  25623. */
  25624. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25625. var _this = this;
  25626. if (timeout !== undefined) {
  25627. setTimeout(function () {
  25628. _this._executeOnceBeforeRender(func);
  25629. }, timeout);
  25630. }
  25631. else {
  25632. this._executeOnceBeforeRender(func);
  25633. }
  25634. };
  25635. /** @hidden */
  25636. Scene.prototype._addPendingData = function (data) {
  25637. this._pendingData.push(data);
  25638. };
  25639. /** @hidden */
  25640. Scene.prototype._removePendingData = function (data) {
  25641. var wasLoading = this.isLoading;
  25642. var index = this._pendingData.indexOf(data);
  25643. if (index !== -1) {
  25644. this._pendingData.splice(index, 1);
  25645. }
  25646. if (wasLoading && !this.isLoading) {
  25647. this.onDataLoadedObservable.notifyObservers(this);
  25648. }
  25649. };
  25650. /**
  25651. * Returns the number of items waiting to be loaded
  25652. * @returns the number of items waiting to be loaded
  25653. */
  25654. Scene.prototype.getWaitingItemsCount = function () {
  25655. return this._pendingData.length;
  25656. };
  25657. Object.defineProperty(Scene.prototype, "isLoading", {
  25658. /**
  25659. * Returns a boolean indicating if the scene is still loading data
  25660. */
  25661. get: function () {
  25662. return this._pendingData.length > 0;
  25663. },
  25664. enumerable: true,
  25665. configurable: true
  25666. });
  25667. /**
  25668. * Registers a function to be executed when the scene is ready
  25669. * @param {Function} func - the function to be executed
  25670. */
  25671. Scene.prototype.executeWhenReady = function (func) {
  25672. var _this = this;
  25673. this.onReadyObservable.add(func);
  25674. if (this._executeWhenReadyTimeoutId !== -1) {
  25675. return;
  25676. }
  25677. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25678. _this._checkIsReady();
  25679. }, 150);
  25680. };
  25681. /**
  25682. * Returns a promise that resolves when the scene is ready
  25683. * @returns A promise that resolves when the scene is ready
  25684. */
  25685. Scene.prototype.whenReadyAsync = function () {
  25686. var _this = this;
  25687. return new Promise(function (resolve) {
  25688. _this.executeWhenReady(function () {
  25689. resolve();
  25690. });
  25691. });
  25692. };
  25693. /** @hidden */
  25694. Scene.prototype._checkIsReady = function () {
  25695. var _this = this;
  25696. this._registerTransientComponents();
  25697. if (this.isReady()) {
  25698. this.onReadyObservable.notifyObservers(this);
  25699. this.onReadyObservable.clear();
  25700. this._executeWhenReadyTimeoutId = -1;
  25701. return;
  25702. }
  25703. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25704. _this._checkIsReady();
  25705. }, 150);
  25706. };
  25707. // Animations
  25708. /**
  25709. * Will start the animation sequence of a given target
  25710. * @param target defines the target
  25711. * @param from defines from which frame should animation start
  25712. * @param to defines until which frame should animation run.
  25713. * @param weight defines the weight to apply to the animation (1.0 by default)
  25714. * @param loop defines if the animation loops
  25715. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25716. * @param onAnimationEnd defines the function to be executed when the animation ends
  25717. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25718. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25719. * @returns the animatable object created for this animation
  25720. */
  25721. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25722. if (weight === void 0) { weight = 1.0; }
  25723. if (speedRatio === void 0) { speedRatio = 1.0; }
  25724. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25725. returnedAnimatable.weight = weight;
  25726. return returnedAnimatable;
  25727. };
  25728. /**
  25729. * Will start the animation sequence of a given target
  25730. * @param target defines the target
  25731. * @param from defines from which frame should animation start
  25732. * @param to defines until which frame should animation run.
  25733. * @param loop defines if the animation loops
  25734. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25735. * @param onAnimationEnd defines the function to be executed when the animation ends
  25736. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25737. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25738. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25739. * @returns the animatable object created for this animation
  25740. */
  25741. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25742. if (speedRatio === void 0) { speedRatio = 1.0; }
  25743. if (stopCurrent === void 0) { stopCurrent = true; }
  25744. if (from > to && speedRatio > 0) {
  25745. speedRatio *= -1;
  25746. }
  25747. if (stopCurrent) {
  25748. this.stopAnimation(target, undefined, targetMask);
  25749. }
  25750. if (!animatable) {
  25751. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25752. }
  25753. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25754. // Local animations
  25755. if (target.animations && shouldRunTargetAnimations) {
  25756. animatable.appendAnimations(target, target.animations);
  25757. }
  25758. // Children animations
  25759. if (target.getAnimatables) {
  25760. var animatables = target.getAnimatables();
  25761. for (var index = 0; index < animatables.length; index++) {
  25762. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25763. }
  25764. }
  25765. animatable.reset();
  25766. return animatable;
  25767. };
  25768. /**
  25769. * Begin a new animation on a given node
  25770. * @param target defines the target where the animation will take place
  25771. * @param animations defines the list of animations to start
  25772. * @param from defines the initial value
  25773. * @param to defines the final value
  25774. * @param loop defines if you want animation to loop (off by default)
  25775. * @param speedRatio defines the speed ratio to apply to all animations
  25776. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25777. * @returns the list of created animatables
  25778. */
  25779. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25780. if (speedRatio === undefined) {
  25781. speedRatio = 1.0;
  25782. }
  25783. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25784. return animatable;
  25785. };
  25786. /**
  25787. * Begin a new animation on a given node and its hierarchy
  25788. * @param target defines the root node where the animation will take place
  25789. * @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.
  25790. * @param animations defines the list of animations to start
  25791. * @param from defines the initial value
  25792. * @param to defines the final value
  25793. * @param loop defines if you want animation to loop (off by default)
  25794. * @param speedRatio defines the speed ratio to apply to all animations
  25795. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25796. * @returns the list of animatables created for all nodes
  25797. */
  25798. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25799. var children = target.getDescendants(directDescendantsOnly);
  25800. var result = [];
  25801. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25802. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25803. var child = children_1[_i];
  25804. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25805. }
  25806. return result;
  25807. };
  25808. /**
  25809. * Gets the animatable associated with a specific target
  25810. * @param target defines the target of the animatable
  25811. * @returns the required animatable if found
  25812. */
  25813. Scene.prototype.getAnimatableByTarget = function (target) {
  25814. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25815. if (this._activeAnimatables[index].target === target) {
  25816. return this._activeAnimatables[index];
  25817. }
  25818. }
  25819. return null;
  25820. };
  25821. /**
  25822. * Gets all animatables associated with a given target
  25823. * @param target defines the target to look animatables for
  25824. * @returns an array of Animatables
  25825. */
  25826. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25827. var result = [];
  25828. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25829. if (this._activeAnimatables[index].target === target) {
  25830. result.push(this._activeAnimatables[index]);
  25831. }
  25832. }
  25833. return result;
  25834. };
  25835. Object.defineProperty(Scene.prototype, "animatables", {
  25836. /**
  25837. * Gets all animatable attached to the scene
  25838. */
  25839. get: function () {
  25840. return this._activeAnimatables;
  25841. },
  25842. enumerable: true,
  25843. configurable: true
  25844. });
  25845. /**
  25846. * Will stop the animation of the given target
  25847. * @param target - the target
  25848. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25849. * @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)
  25850. */
  25851. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25852. var animatables = this.getAllAnimatablesByTarget(target);
  25853. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25854. var animatable = animatables_1[_i];
  25855. animatable.stop(animationName, targetMask);
  25856. }
  25857. };
  25858. /**
  25859. * Stops and removes all animations that have been applied to the scene
  25860. */
  25861. Scene.prototype.stopAllAnimations = function () {
  25862. if (this._activeAnimatables) {
  25863. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25864. this._activeAnimatables[i].stop();
  25865. }
  25866. this._activeAnimatables = [];
  25867. }
  25868. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25869. var group = _a[_i];
  25870. group.stop();
  25871. }
  25872. };
  25873. Scene.prototype._animate = function () {
  25874. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25875. return;
  25876. }
  25877. // Getting time
  25878. var now = BABYLON.Tools.Now;
  25879. if (!this._animationTimeLast) {
  25880. if (this._pendingData.length > 0) {
  25881. return;
  25882. }
  25883. this._animationTimeLast = now;
  25884. }
  25885. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25886. this._animationTime += deltaTime;
  25887. this._animationTimeLast = now;
  25888. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25889. this._activeAnimatables[index]._animate(this._animationTime);
  25890. }
  25891. // Late animation bindings
  25892. this._processLateAnimationBindings();
  25893. };
  25894. /** @hidden */
  25895. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25896. var target = runtimeAnimation.target;
  25897. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25898. if (!target._lateAnimationHolders) {
  25899. target._lateAnimationHolders = {};
  25900. }
  25901. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25902. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25903. totalWeight: 0,
  25904. animations: [],
  25905. originalValue: originalValue
  25906. };
  25907. }
  25908. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25909. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25910. };
  25911. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25912. var normalizer = 1.0;
  25913. var finalPosition = BABYLON.Tmp.Vector3[0];
  25914. var finalScaling = BABYLON.Tmp.Vector3[1];
  25915. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25916. var startIndex = 0;
  25917. var originalAnimation = holder.animations[0];
  25918. var originalValue = holder.originalValue;
  25919. var scale = 1;
  25920. if (holder.totalWeight < 1.0) {
  25921. // We need to mix the original value in
  25922. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25923. scale = 1.0 - holder.totalWeight;
  25924. }
  25925. else {
  25926. startIndex = 1;
  25927. // We need to normalize the weights
  25928. normalizer = holder.totalWeight;
  25929. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25930. scale = originalAnimation.weight / normalizer;
  25931. if (scale == 1) {
  25932. return originalAnimation.currentValue;
  25933. }
  25934. }
  25935. finalScaling.scaleInPlace(scale);
  25936. finalPosition.scaleInPlace(scale);
  25937. finalQuaternion.scaleInPlace(scale);
  25938. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25939. var runtimeAnimation = holder.animations[animIndex];
  25940. var scale = runtimeAnimation.weight / normalizer;
  25941. var currentPosition = BABYLON.Tmp.Vector3[2];
  25942. var currentScaling = BABYLON.Tmp.Vector3[3];
  25943. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25944. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25945. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25946. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25947. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25948. }
  25949. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25950. return originalAnimation._workValue;
  25951. };
  25952. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25953. var originalAnimation = holder.animations[0];
  25954. var originalValue = holder.originalValue;
  25955. if (holder.animations.length === 1) {
  25956. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25957. }
  25958. var normalizer = 1.0;
  25959. var quaternions;
  25960. var weights;
  25961. if (holder.totalWeight < 1.0) {
  25962. var scale = 1.0 - holder.totalWeight;
  25963. quaternions = [];
  25964. weights = [];
  25965. quaternions.push(originalValue);
  25966. weights.push(scale);
  25967. }
  25968. else {
  25969. if (holder.animations.length === 2) { // Slerp as soon as we can
  25970. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25971. }
  25972. quaternions = [];
  25973. weights = [];
  25974. normalizer = holder.totalWeight;
  25975. }
  25976. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25977. var runtimeAnimation = holder.animations[animIndex];
  25978. quaternions.push(runtimeAnimation.currentValue);
  25979. weights.push(runtimeAnimation.weight / normalizer);
  25980. }
  25981. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25982. var cumulativeAmount = 0;
  25983. var cumulativeQuaternion = null;
  25984. for (var index = 0; index < quaternions.length;) {
  25985. if (!cumulativeQuaternion) {
  25986. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25987. cumulativeAmount = weights[index] + weights[index + 1];
  25988. index += 2;
  25989. continue;
  25990. }
  25991. cumulativeAmount += weights[index];
  25992. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25993. index++;
  25994. }
  25995. return cumulativeQuaternion;
  25996. };
  25997. Scene.prototype._processLateAnimationBindings = function () {
  25998. if (!this._registeredForLateAnimationBindings.length) {
  25999. return;
  26000. }
  26001. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26002. var target = this._registeredForLateAnimationBindings.data[index];
  26003. for (var path in target._lateAnimationHolders) {
  26004. var holder = target._lateAnimationHolders[path];
  26005. var originalAnimation = holder.animations[0];
  26006. var originalValue = holder.originalValue;
  26007. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26008. var finalValue = void 0;
  26009. if (matrixDecomposeMode) {
  26010. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26011. }
  26012. else {
  26013. var quaternionMode = originalValue.w !== undefined;
  26014. if (quaternionMode) {
  26015. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26016. }
  26017. else {
  26018. var startIndex = 0;
  26019. var normalizer = 1.0;
  26020. if (holder.totalWeight < 1.0) {
  26021. // We need to mix the original value in
  26022. if (originalValue.scale) {
  26023. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26024. }
  26025. else {
  26026. finalValue = originalValue * (1.0 - holder.totalWeight);
  26027. }
  26028. }
  26029. else {
  26030. // We need to normalize the weights
  26031. normalizer = holder.totalWeight;
  26032. var scale_1 = originalAnimation.weight / normalizer;
  26033. if (scale_1 !== 1) {
  26034. if (originalAnimation.currentValue.scale) {
  26035. finalValue = originalAnimation.currentValue.scale(scale_1);
  26036. }
  26037. else {
  26038. finalValue = originalAnimation.currentValue * scale_1;
  26039. }
  26040. }
  26041. else {
  26042. finalValue = originalAnimation.currentValue;
  26043. }
  26044. startIndex = 1;
  26045. }
  26046. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26047. var runtimeAnimation = holder.animations[animIndex];
  26048. var scale = runtimeAnimation.weight / normalizer;
  26049. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26050. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26051. }
  26052. else {
  26053. finalValue += runtimeAnimation.currentValue * scale;
  26054. }
  26055. }
  26056. }
  26057. }
  26058. target[path] = finalValue;
  26059. }
  26060. target._lateAnimationHolders = {};
  26061. }
  26062. this._registeredForLateAnimationBindings.reset();
  26063. };
  26064. // Matrix
  26065. /** @hidden */
  26066. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26067. this._useAlternateCameraConfiguration = active;
  26068. };
  26069. /**
  26070. * Gets the current view matrix
  26071. * @returns a Matrix
  26072. */
  26073. Scene.prototype.getViewMatrix = function () {
  26074. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26075. };
  26076. /**
  26077. * Gets the current projection matrix
  26078. * @returns a Matrix
  26079. */
  26080. Scene.prototype.getProjectionMatrix = function () {
  26081. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26082. };
  26083. /**
  26084. * Gets the current transform matrix
  26085. * @returns a Matrix made of View * Projection
  26086. */
  26087. Scene.prototype.getTransformMatrix = function () {
  26088. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26089. };
  26090. /**
  26091. * Sets the current transform matrix
  26092. * @param view defines the View matrix to use
  26093. * @param projection defines the Projection matrix to use
  26094. */
  26095. Scene.prototype.setTransformMatrix = function (view, projection) {
  26096. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26097. return;
  26098. }
  26099. this._viewUpdateFlag = view.updateFlag;
  26100. this._projectionUpdateFlag = projection.updateFlag;
  26101. this._viewMatrix = view;
  26102. this._projectionMatrix = projection;
  26103. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26104. // Update frustum
  26105. if (!this._frustumPlanes) {
  26106. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26107. }
  26108. else {
  26109. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26110. }
  26111. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26112. var otherCamera = this.activeCamera._alternateCamera;
  26113. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26114. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26115. }
  26116. if (this._sceneUbo.useUbo) {
  26117. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26118. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26119. this._sceneUbo.update();
  26120. }
  26121. };
  26122. /** @hidden */
  26123. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26124. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26125. return;
  26126. }
  26127. this._alternateViewUpdateFlag = view.updateFlag;
  26128. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26129. this._alternateViewMatrix = view;
  26130. this._alternateProjectionMatrix = projection;
  26131. if (!this._alternateTransformMatrix) {
  26132. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26133. }
  26134. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26135. if (!this._alternateSceneUbo) {
  26136. this._createAlternateUbo();
  26137. }
  26138. if (this._alternateSceneUbo.useUbo) {
  26139. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26140. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26141. this._alternateSceneUbo.update();
  26142. }
  26143. };
  26144. /**
  26145. * Gets the uniform buffer used to store scene data
  26146. * @returns a UniformBuffer
  26147. */
  26148. Scene.prototype.getSceneUniformBuffer = function () {
  26149. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26150. };
  26151. /**
  26152. * Gets an unique (relatively to the current scene) Id
  26153. * @returns an unique number for the scene
  26154. */
  26155. Scene.prototype.getUniqueId = function () {
  26156. var result = Scene._uniqueIdCounter;
  26157. Scene._uniqueIdCounter++;
  26158. return result;
  26159. };
  26160. /**
  26161. * Add a mesh to the list of scene's meshes
  26162. * @param newMesh defines the mesh to add
  26163. * @param recursive if all child meshes should also be added to the scene
  26164. */
  26165. Scene.prototype.addMesh = function (newMesh, recursive) {
  26166. var _this = this;
  26167. if (recursive === void 0) { recursive = false; }
  26168. this.meshes.push(newMesh);
  26169. //notify the collision coordinator
  26170. if (this.collisionCoordinator) {
  26171. this.collisionCoordinator.onMeshAdded(newMesh);
  26172. }
  26173. newMesh._resyncLightSources();
  26174. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26175. if (recursive) {
  26176. newMesh.getChildMeshes().forEach(function (m) {
  26177. _this.addMesh(m);
  26178. });
  26179. }
  26180. };
  26181. /**
  26182. * Remove a mesh for the list of scene's meshes
  26183. * @param toRemove defines the mesh to remove
  26184. * @param recursive if all child meshes should also be removed from the scene
  26185. * @returns the index where the mesh was in the mesh list
  26186. */
  26187. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26188. var _this = this;
  26189. if (recursive === void 0) { recursive = false; }
  26190. var index = this.meshes.indexOf(toRemove);
  26191. if (index !== -1) {
  26192. // Remove from the scene if mesh found
  26193. this.meshes.splice(index, 1);
  26194. }
  26195. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26196. if (recursive) {
  26197. toRemove.getChildMeshes().forEach(function (m) {
  26198. _this.removeMesh(m);
  26199. });
  26200. }
  26201. return index;
  26202. };
  26203. /**
  26204. * Add a transform node to the list of scene's transform nodes
  26205. * @param newTransformNode defines the transform node to add
  26206. */
  26207. Scene.prototype.addTransformNode = function (newTransformNode) {
  26208. this.transformNodes.push(newTransformNode);
  26209. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26210. };
  26211. /**
  26212. * Remove a transform node for the list of scene's transform nodes
  26213. * @param toRemove defines the transform node to remove
  26214. * @returns the index where the transform node was in the transform node list
  26215. */
  26216. Scene.prototype.removeTransformNode = function (toRemove) {
  26217. var index = this.transformNodes.indexOf(toRemove);
  26218. if (index !== -1) {
  26219. // Remove from the scene if found
  26220. this.transformNodes.splice(index, 1);
  26221. }
  26222. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26223. return index;
  26224. };
  26225. /**
  26226. * Remove a skeleton for the list of scene's skeletons
  26227. * @param toRemove defines the skeleton to remove
  26228. * @returns the index where the skeleton was in the skeleton list
  26229. */
  26230. Scene.prototype.removeSkeleton = function (toRemove) {
  26231. var index = this.skeletons.indexOf(toRemove);
  26232. if (index !== -1) {
  26233. // Remove from the scene if found
  26234. this.skeletons.splice(index, 1);
  26235. }
  26236. return index;
  26237. };
  26238. /**
  26239. * Remove a morph target for the list of scene's morph targets
  26240. * @param toRemove defines the morph target to remove
  26241. * @returns the index where the morph target was in the morph target list
  26242. */
  26243. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26244. var index = this.morphTargetManagers.indexOf(toRemove);
  26245. if (index !== -1) {
  26246. // Remove from the scene if found
  26247. this.morphTargetManagers.splice(index, 1);
  26248. }
  26249. return index;
  26250. };
  26251. /**
  26252. * Remove a light for the list of scene's lights
  26253. * @param toRemove defines the light to remove
  26254. * @returns the index where the light was in the light list
  26255. */
  26256. Scene.prototype.removeLight = function (toRemove) {
  26257. var index = this.lights.indexOf(toRemove);
  26258. if (index !== -1) {
  26259. // Remove from meshes
  26260. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26261. var mesh = _a[_i];
  26262. mesh._removeLightSource(toRemove);
  26263. }
  26264. // Remove from the scene if mesh found
  26265. this.lights.splice(index, 1);
  26266. this.sortLightsByPriority();
  26267. }
  26268. this.onLightRemovedObservable.notifyObservers(toRemove);
  26269. return index;
  26270. };
  26271. /**
  26272. * Remove a camera for the list of scene's cameras
  26273. * @param toRemove defines the camera to remove
  26274. * @returns the index where the camera was in the camera list
  26275. */
  26276. Scene.prototype.removeCamera = function (toRemove) {
  26277. var index = this.cameras.indexOf(toRemove);
  26278. if (index !== -1) {
  26279. // Remove from the scene if mesh found
  26280. this.cameras.splice(index, 1);
  26281. }
  26282. // Remove from activeCameras
  26283. var index2 = this.activeCameras.indexOf(toRemove);
  26284. if (index2 !== -1) {
  26285. // Remove from the scene if mesh found
  26286. this.activeCameras.splice(index2, 1);
  26287. }
  26288. // Reset the activeCamera
  26289. if (this.activeCamera === toRemove) {
  26290. if (this.cameras.length > 0) {
  26291. this.activeCamera = this.cameras[0];
  26292. }
  26293. else {
  26294. this.activeCamera = null;
  26295. }
  26296. }
  26297. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26298. return index;
  26299. };
  26300. /**
  26301. * Remove a particle system for the list of scene's particle systems
  26302. * @param toRemove defines the particle system to remove
  26303. * @returns the index where the particle system was in the particle system list
  26304. */
  26305. Scene.prototype.removeParticleSystem = function (toRemove) {
  26306. var index = this.particleSystems.indexOf(toRemove);
  26307. if (index !== -1) {
  26308. this.particleSystems.splice(index, 1);
  26309. }
  26310. return index;
  26311. };
  26312. /**
  26313. * Remove a animation for the list of scene's animations
  26314. * @param toRemove defines the animation to remove
  26315. * @returns the index where the animation was in the animation list
  26316. */
  26317. Scene.prototype.removeAnimation = function (toRemove) {
  26318. var index = this.animations.indexOf(toRemove);
  26319. if (index !== -1) {
  26320. this.animations.splice(index, 1);
  26321. }
  26322. return index;
  26323. };
  26324. /**
  26325. * Removes the given animation group from this scene.
  26326. * @param toRemove The animation group to remove
  26327. * @returns The index of the removed animation group
  26328. */
  26329. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26330. var index = this.animationGroups.indexOf(toRemove);
  26331. if (index !== -1) {
  26332. this.animationGroups.splice(index, 1);
  26333. }
  26334. return index;
  26335. };
  26336. /**
  26337. * Removes the given multi-material from this scene.
  26338. * @param toRemove The multi-material to remove
  26339. * @returns The index of the removed multi-material
  26340. */
  26341. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26342. var index = this.multiMaterials.indexOf(toRemove);
  26343. if (index !== -1) {
  26344. this.multiMaterials.splice(index, 1);
  26345. }
  26346. return index;
  26347. };
  26348. /**
  26349. * Removes the given material from this scene.
  26350. * @param toRemove The material to remove
  26351. * @returns The index of the removed material
  26352. */
  26353. Scene.prototype.removeMaterial = function (toRemove) {
  26354. var index = this.materials.indexOf(toRemove);
  26355. if (index !== -1) {
  26356. this.materials.splice(index, 1);
  26357. }
  26358. return index;
  26359. };
  26360. /**
  26361. * Removes the given action manager from this scene.
  26362. * @param toRemove The action manager to remove
  26363. * @returns The index of the removed action manager
  26364. */
  26365. Scene.prototype.removeActionManager = function (toRemove) {
  26366. var index = this.actionManagers.indexOf(toRemove);
  26367. if (index !== -1) {
  26368. this.actionManagers.splice(index, 1);
  26369. }
  26370. return index;
  26371. };
  26372. /**
  26373. * Removes the given texture from this scene.
  26374. * @param toRemove The texture to remove
  26375. * @returns The index of the removed texture
  26376. */
  26377. Scene.prototype.removeTexture = function (toRemove) {
  26378. var index = this.textures.indexOf(toRemove);
  26379. if (index !== -1) {
  26380. this.textures.splice(index, 1);
  26381. }
  26382. return index;
  26383. };
  26384. /**
  26385. * Adds the given light to this scene
  26386. * @param newLight The light to add
  26387. */
  26388. Scene.prototype.addLight = function (newLight) {
  26389. this.lights.push(newLight);
  26390. this.sortLightsByPriority();
  26391. // Add light to all meshes (To support if the light is removed and then readded)
  26392. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26393. var mesh = _a[_i];
  26394. if (mesh._lightSources.indexOf(newLight) === -1) {
  26395. mesh._lightSources.push(newLight);
  26396. mesh._resyncLightSources();
  26397. }
  26398. }
  26399. this.onNewLightAddedObservable.notifyObservers(newLight);
  26400. };
  26401. /**
  26402. * Sorts the list list based on light priorities
  26403. */
  26404. Scene.prototype.sortLightsByPriority = function () {
  26405. if (this.requireLightSorting) {
  26406. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26407. }
  26408. };
  26409. /**
  26410. * Adds the given camera to this scene
  26411. * @param newCamera The camera to add
  26412. */
  26413. Scene.prototype.addCamera = function (newCamera) {
  26414. this.cameras.push(newCamera);
  26415. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26416. };
  26417. /**
  26418. * Adds the given skeleton to this scene
  26419. * @param newSkeleton The skeleton to add
  26420. */
  26421. Scene.prototype.addSkeleton = function (newSkeleton) {
  26422. this.skeletons.push(newSkeleton);
  26423. };
  26424. /**
  26425. * Adds the given particle system to this scene
  26426. * @param newParticleSystem The particle system to add
  26427. */
  26428. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26429. this.particleSystems.push(newParticleSystem);
  26430. };
  26431. /**
  26432. * Adds the given animation to this scene
  26433. * @param newAnimation The animation to add
  26434. */
  26435. Scene.prototype.addAnimation = function (newAnimation) {
  26436. this.animations.push(newAnimation);
  26437. };
  26438. /**
  26439. * Adds the given animation group to this scene.
  26440. * @param newAnimationGroup The animation group to add
  26441. */
  26442. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26443. this.animationGroups.push(newAnimationGroup);
  26444. };
  26445. /**
  26446. * Adds the given multi-material to this scene
  26447. * @param newMultiMaterial The multi-material to add
  26448. */
  26449. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26450. this.multiMaterials.push(newMultiMaterial);
  26451. };
  26452. /**
  26453. * Adds the given material to this scene
  26454. * @param newMaterial The material to add
  26455. */
  26456. Scene.prototype.addMaterial = function (newMaterial) {
  26457. this.materials.push(newMaterial);
  26458. };
  26459. /**
  26460. * Adds the given morph target to this scene
  26461. * @param newMorphTargetManager The morph target to add
  26462. */
  26463. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26464. this.morphTargetManagers.push(newMorphTargetManager);
  26465. };
  26466. /**
  26467. * Adds the given geometry to this scene
  26468. * @param newGeometry The geometry to add
  26469. */
  26470. Scene.prototype.addGeometry = function (newGeometry) {
  26471. this.geometries.push(newGeometry);
  26472. };
  26473. /**
  26474. * Adds the given action manager to this scene
  26475. * @param newActionManager The action manager to add
  26476. */
  26477. Scene.prototype.addActionManager = function (newActionManager) {
  26478. this.actionManagers.push(newActionManager);
  26479. };
  26480. /**
  26481. * Adds the given texture to this scene.
  26482. * @param newTexture The texture to add
  26483. */
  26484. Scene.prototype.addTexture = function (newTexture) {
  26485. this.textures.push(newTexture);
  26486. };
  26487. /**
  26488. * Switch active camera
  26489. * @param newCamera defines the new active camera
  26490. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26491. */
  26492. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26493. if (attachControl === void 0) { attachControl = true; }
  26494. var canvas = this._engine.getRenderingCanvas();
  26495. if (!canvas) {
  26496. return;
  26497. }
  26498. if (this.activeCamera) {
  26499. this.activeCamera.detachControl(canvas);
  26500. }
  26501. this.activeCamera = newCamera;
  26502. if (attachControl) {
  26503. newCamera.attachControl(canvas);
  26504. }
  26505. };
  26506. /**
  26507. * sets the active camera of the scene using its ID
  26508. * @param id defines the camera's ID
  26509. * @return the new active camera or null if none found.
  26510. */
  26511. Scene.prototype.setActiveCameraByID = function (id) {
  26512. var camera = this.getCameraByID(id);
  26513. if (camera) {
  26514. this.activeCamera = camera;
  26515. return camera;
  26516. }
  26517. return null;
  26518. };
  26519. /**
  26520. * sets the active camera of the scene using its name
  26521. * @param name defines the camera's name
  26522. * @returns the new active camera or null if none found.
  26523. */
  26524. Scene.prototype.setActiveCameraByName = function (name) {
  26525. var camera = this.getCameraByName(name);
  26526. if (camera) {
  26527. this.activeCamera = camera;
  26528. return camera;
  26529. }
  26530. return null;
  26531. };
  26532. /**
  26533. * get an animation group using its name
  26534. * @param name defines the material's name
  26535. * @return the animation group or null if none found.
  26536. */
  26537. Scene.prototype.getAnimationGroupByName = function (name) {
  26538. for (var index = 0; index < this.animationGroups.length; index++) {
  26539. if (this.animationGroups[index].name === name) {
  26540. return this.animationGroups[index];
  26541. }
  26542. }
  26543. return null;
  26544. };
  26545. /**
  26546. * get a material using its id
  26547. * @param id defines the material's ID
  26548. * @return the material or null if none found.
  26549. */
  26550. Scene.prototype.getMaterialByID = function (id) {
  26551. for (var index = 0; index < this.materials.length; index++) {
  26552. if (this.materials[index].id === id) {
  26553. return this.materials[index];
  26554. }
  26555. }
  26556. return null;
  26557. };
  26558. /**
  26559. * Gets a material using its name
  26560. * @param name defines the material's name
  26561. * @return the material or null if none found.
  26562. */
  26563. Scene.prototype.getMaterialByName = function (name) {
  26564. for (var index = 0; index < this.materials.length; index++) {
  26565. if (this.materials[index].name === name) {
  26566. return this.materials[index];
  26567. }
  26568. }
  26569. return null;
  26570. };
  26571. /**
  26572. * Gets a camera using its id
  26573. * @param id defines the id to look for
  26574. * @returns the camera or null if not found
  26575. */
  26576. Scene.prototype.getCameraByID = function (id) {
  26577. for (var index = 0; index < this.cameras.length; index++) {
  26578. if (this.cameras[index].id === id) {
  26579. return this.cameras[index];
  26580. }
  26581. }
  26582. return null;
  26583. };
  26584. /**
  26585. * Gets a camera using its unique id
  26586. * @param uniqueId defines the unique id to look for
  26587. * @returns the camera or null if not found
  26588. */
  26589. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26590. for (var index = 0; index < this.cameras.length; index++) {
  26591. if (this.cameras[index].uniqueId === uniqueId) {
  26592. return this.cameras[index];
  26593. }
  26594. }
  26595. return null;
  26596. };
  26597. /**
  26598. * Gets a camera using its name
  26599. * @param name defines the camera's name
  26600. * @return the camera or null if none found.
  26601. */
  26602. Scene.prototype.getCameraByName = function (name) {
  26603. for (var index = 0; index < this.cameras.length; index++) {
  26604. if (this.cameras[index].name === name) {
  26605. return this.cameras[index];
  26606. }
  26607. }
  26608. return null;
  26609. };
  26610. /**
  26611. * Gets a bone using its id
  26612. * @param id defines the bone's id
  26613. * @return the bone or null if not found
  26614. */
  26615. Scene.prototype.getBoneByID = function (id) {
  26616. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26617. var skeleton = this.skeletons[skeletonIndex];
  26618. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26619. if (skeleton.bones[boneIndex].id === id) {
  26620. return skeleton.bones[boneIndex];
  26621. }
  26622. }
  26623. }
  26624. return null;
  26625. };
  26626. /**
  26627. * Gets a bone using its id
  26628. * @param name defines the bone's name
  26629. * @return the bone or null if not found
  26630. */
  26631. Scene.prototype.getBoneByName = function (name) {
  26632. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26633. var skeleton = this.skeletons[skeletonIndex];
  26634. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26635. if (skeleton.bones[boneIndex].name === name) {
  26636. return skeleton.bones[boneIndex];
  26637. }
  26638. }
  26639. }
  26640. return null;
  26641. };
  26642. /**
  26643. * Gets a light node using its name
  26644. * @param name defines the the light's name
  26645. * @return the light or null if none found.
  26646. */
  26647. Scene.prototype.getLightByName = function (name) {
  26648. for (var index = 0; index < this.lights.length; index++) {
  26649. if (this.lights[index].name === name) {
  26650. return this.lights[index];
  26651. }
  26652. }
  26653. return null;
  26654. };
  26655. /**
  26656. * Gets a light node using its id
  26657. * @param id defines the light's id
  26658. * @return the light or null if none found.
  26659. */
  26660. Scene.prototype.getLightByID = function (id) {
  26661. for (var index = 0; index < this.lights.length; index++) {
  26662. if (this.lights[index].id === id) {
  26663. return this.lights[index];
  26664. }
  26665. }
  26666. return null;
  26667. };
  26668. /**
  26669. * Gets a light node using its scene-generated unique ID
  26670. * @param uniqueId defines the light's unique id
  26671. * @return the light or null if none found.
  26672. */
  26673. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26674. for (var index = 0; index < this.lights.length; index++) {
  26675. if (this.lights[index].uniqueId === uniqueId) {
  26676. return this.lights[index];
  26677. }
  26678. }
  26679. return null;
  26680. };
  26681. /**
  26682. * Gets a particle system by id
  26683. * @param id defines the particle system id
  26684. * @return the corresponding system or null if none found
  26685. */
  26686. Scene.prototype.getParticleSystemByID = function (id) {
  26687. for (var index = 0; index < this.particleSystems.length; index++) {
  26688. if (this.particleSystems[index].id === id) {
  26689. return this.particleSystems[index];
  26690. }
  26691. }
  26692. return null;
  26693. };
  26694. /**
  26695. * Gets a geometry using its ID
  26696. * @param id defines the geometry's id
  26697. * @return the geometry or null if none found.
  26698. */
  26699. Scene.prototype.getGeometryByID = function (id) {
  26700. for (var index = 0; index < this.geometries.length; index++) {
  26701. if (this.geometries[index].id === id) {
  26702. return this.geometries[index];
  26703. }
  26704. }
  26705. return null;
  26706. };
  26707. /**
  26708. * Add a new geometry to this scene
  26709. * @param geometry defines the geometry to be added to the scene.
  26710. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26711. * @return a boolean defining if the geometry was added or not
  26712. */
  26713. Scene.prototype.pushGeometry = function (geometry, force) {
  26714. if (!force && this.getGeometryByID(geometry.id)) {
  26715. return false;
  26716. }
  26717. this.geometries.push(geometry);
  26718. //notify the collision coordinator
  26719. if (this.collisionCoordinator) {
  26720. this.collisionCoordinator.onGeometryAdded(geometry);
  26721. }
  26722. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26723. return true;
  26724. };
  26725. /**
  26726. * Removes an existing geometry
  26727. * @param geometry defines the geometry to be removed from the scene
  26728. * @return a boolean defining if the geometry was removed or not
  26729. */
  26730. Scene.prototype.removeGeometry = function (geometry) {
  26731. var index = this.geometries.indexOf(geometry);
  26732. if (index > -1) {
  26733. this.geometries.splice(index, 1);
  26734. //notify the collision coordinator
  26735. if (this.collisionCoordinator) {
  26736. this.collisionCoordinator.onGeometryDeleted(geometry);
  26737. }
  26738. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26739. return true;
  26740. }
  26741. return false;
  26742. };
  26743. /**
  26744. * Gets the list of geometries attached to the scene
  26745. * @returns an array of Geometry
  26746. */
  26747. Scene.prototype.getGeometries = function () {
  26748. return this.geometries;
  26749. };
  26750. /**
  26751. * Gets the first added mesh found of a given ID
  26752. * @param id defines the id to search for
  26753. * @return the mesh found or null if not found at all
  26754. */
  26755. Scene.prototype.getMeshByID = function (id) {
  26756. for (var index = 0; index < this.meshes.length; index++) {
  26757. if (this.meshes[index].id === id) {
  26758. return this.meshes[index];
  26759. }
  26760. }
  26761. return null;
  26762. };
  26763. /**
  26764. * Gets a list of meshes using their id
  26765. * @param id defines the id to search for
  26766. * @returns a list of meshes
  26767. */
  26768. Scene.prototype.getMeshesByID = function (id) {
  26769. return this.meshes.filter(function (m) {
  26770. return m.id === id;
  26771. });
  26772. };
  26773. /**
  26774. * Gets the first added transform node found of a given ID
  26775. * @param id defines the id to search for
  26776. * @return the found transform node or null if not found at all.
  26777. */
  26778. Scene.prototype.getTransformNodeByID = function (id) {
  26779. for (var index = 0; index < this.transformNodes.length; index++) {
  26780. if (this.transformNodes[index].id === id) {
  26781. return this.transformNodes[index];
  26782. }
  26783. }
  26784. return null;
  26785. };
  26786. /**
  26787. * Gets a list of transform nodes using their id
  26788. * @param id defines the id to search for
  26789. * @returns a list of transform nodes
  26790. */
  26791. Scene.prototype.getTransformNodesByID = function (id) {
  26792. return this.transformNodes.filter(function (m) {
  26793. return m.id === id;
  26794. });
  26795. };
  26796. /**
  26797. * Gets a mesh with its auto-generated unique id
  26798. * @param uniqueId defines the unique id to search for
  26799. * @return the found mesh or null if not found at all.
  26800. */
  26801. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26802. for (var index = 0; index < this.meshes.length; index++) {
  26803. if (this.meshes[index].uniqueId === uniqueId) {
  26804. return this.meshes[index];
  26805. }
  26806. }
  26807. return null;
  26808. };
  26809. /**
  26810. * Gets a the last added mesh using a given id
  26811. * @param id defines the id to search for
  26812. * @return the found mesh or null if not found at all.
  26813. */
  26814. Scene.prototype.getLastMeshByID = function (id) {
  26815. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26816. if (this.meshes[index].id === id) {
  26817. return this.meshes[index];
  26818. }
  26819. }
  26820. return null;
  26821. };
  26822. /**
  26823. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26824. * @param id defines the id to search for
  26825. * @return the found node or null if not found at all
  26826. */
  26827. Scene.prototype.getLastEntryByID = function (id) {
  26828. var index;
  26829. for (index = this.meshes.length - 1; index >= 0; index--) {
  26830. if (this.meshes[index].id === id) {
  26831. return this.meshes[index];
  26832. }
  26833. }
  26834. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26835. if (this.transformNodes[index].id === id) {
  26836. return this.transformNodes[index];
  26837. }
  26838. }
  26839. for (index = this.cameras.length - 1; index >= 0; index--) {
  26840. if (this.cameras[index].id === id) {
  26841. return this.cameras[index];
  26842. }
  26843. }
  26844. for (index = this.lights.length - 1; index >= 0; index--) {
  26845. if (this.lights[index].id === id) {
  26846. return this.lights[index];
  26847. }
  26848. }
  26849. return null;
  26850. };
  26851. /**
  26852. * Gets a node (Mesh, Camera, Light) using a given id
  26853. * @param id defines the id to search for
  26854. * @return the found node or null if not found at all
  26855. */
  26856. Scene.prototype.getNodeByID = function (id) {
  26857. var mesh = this.getMeshByID(id);
  26858. if (mesh) {
  26859. return mesh;
  26860. }
  26861. var light = this.getLightByID(id);
  26862. if (light) {
  26863. return light;
  26864. }
  26865. var camera = this.getCameraByID(id);
  26866. if (camera) {
  26867. return camera;
  26868. }
  26869. var bone = this.getBoneByID(id);
  26870. return bone;
  26871. };
  26872. /**
  26873. * Gets a node (Mesh, Camera, Light) using a given name
  26874. * @param name defines the name to search for
  26875. * @return the found node or null if not found at all.
  26876. */
  26877. Scene.prototype.getNodeByName = function (name) {
  26878. var mesh = this.getMeshByName(name);
  26879. if (mesh) {
  26880. return mesh;
  26881. }
  26882. var light = this.getLightByName(name);
  26883. if (light) {
  26884. return light;
  26885. }
  26886. var camera = this.getCameraByName(name);
  26887. if (camera) {
  26888. return camera;
  26889. }
  26890. var bone = this.getBoneByName(name);
  26891. return bone;
  26892. };
  26893. /**
  26894. * Gets a mesh using a given name
  26895. * @param name defines the name to search for
  26896. * @return the found mesh or null if not found at all.
  26897. */
  26898. Scene.prototype.getMeshByName = function (name) {
  26899. for (var index = 0; index < this.meshes.length; index++) {
  26900. if (this.meshes[index].name === name) {
  26901. return this.meshes[index];
  26902. }
  26903. }
  26904. return null;
  26905. };
  26906. /**
  26907. * Gets a transform node using a given name
  26908. * @param name defines the name to search for
  26909. * @return the found transform node or null if not found at all.
  26910. */
  26911. Scene.prototype.getTransformNodeByName = function (name) {
  26912. for (var index = 0; index < this.transformNodes.length; index++) {
  26913. if (this.transformNodes[index].name === name) {
  26914. return this.transformNodes[index];
  26915. }
  26916. }
  26917. return null;
  26918. };
  26919. /**
  26920. * Gets a sound using a given name
  26921. * @param name defines the name to search for
  26922. * @return the found sound or null if not found at all.
  26923. */
  26924. Scene.prototype.getSoundByName = function (name) {
  26925. var index;
  26926. if (BABYLON.AudioEngine) {
  26927. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26928. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26929. return this.mainSoundTrack.soundCollection[index];
  26930. }
  26931. }
  26932. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26933. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26934. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26935. return this.soundTracks[sdIndex].soundCollection[index];
  26936. }
  26937. }
  26938. }
  26939. }
  26940. return null;
  26941. };
  26942. /**
  26943. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26944. * @param id defines the id to search for
  26945. * @return the found skeleton or null if not found at all.
  26946. */
  26947. Scene.prototype.getLastSkeletonByID = function (id) {
  26948. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26949. if (this.skeletons[index].id === id) {
  26950. return this.skeletons[index];
  26951. }
  26952. }
  26953. return null;
  26954. };
  26955. /**
  26956. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26957. * @param id defines the id to search for
  26958. * @return the found skeleton or null if not found at all.
  26959. */
  26960. Scene.prototype.getSkeletonById = function (id) {
  26961. for (var index = 0; index < this.skeletons.length; index++) {
  26962. if (this.skeletons[index].id === id) {
  26963. return this.skeletons[index];
  26964. }
  26965. }
  26966. return null;
  26967. };
  26968. /**
  26969. * Gets a skeleton using a given name
  26970. * @param name defines the name to search for
  26971. * @return the found skeleton or null if not found at all.
  26972. */
  26973. Scene.prototype.getSkeletonByName = function (name) {
  26974. for (var index = 0; index < this.skeletons.length; index++) {
  26975. if (this.skeletons[index].name === name) {
  26976. return this.skeletons[index];
  26977. }
  26978. }
  26979. return null;
  26980. };
  26981. /**
  26982. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26983. * @param id defines the id to search for
  26984. * @return the found morph target manager or null if not found at all.
  26985. */
  26986. Scene.prototype.getMorphTargetManagerById = function (id) {
  26987. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26988. if (this.morphTargetManagers[index].uniqueId === id) {
  26989. return this.morphTargetManagers[index];
  26990. }
  26991. }
  26992. return null;
  26993. };
  26994. /**
  26995. * Gets a boolean indicating if the given mesh is active
  26996. * @param mesh defines the mesh to look for
  26997. * @returns true if the mesh is in the active list
  26998. */
  26999. Scene.prototype.isActiveMesh = function (mesh) {
  27000. return (this._activeMeshes.indexOf(mesh) !== -1);
  27001. };
  27002. Object.defineProperty(Scene.prototype, "uid", {
  27003. /**
  27004. * Return a unique id as a string which can serve as an identifier for the scene
  27005. */
  27006. get: function () {
  27007. if (!this._uid) {
  27008. this._uid = BABYLON.Tools.RandomId();
  27009. }
  27010. return this._uid;
  27011. },
  27012. enumerable: true,
  27013. configurable: true
  27014. });
  27015. /**
  27016. * Add an externaly attached data from its key.
  27017. * This method call will fail and return false, if such key already exists.
  27018. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27019. * @param key the unique key that identifies the data
  27020. * @param data the data object to associate to the key for this Engine instance
  27021. * @return true if no such key were already present and the data was added successfully, false otherwise
  27022. */
  27023. Scene.prototype.addExternalData = function (key, data) {
  27024. if (!this._externalData) {
  27025. this._externalData = new BABYLON.StringDictionary();
  27026. }
  27027. return this._externalData.add(key, data);
  27028. };
  27029. /**
  27030. * Get an externaly attached data from its key
  27031. * @param key the unique key that identifies the data
  27032. * @return the associated data, if present (can be null), or undefined if not present
  27033. */
  27034. Scene.prototype.getExternalData = function (key) {
  27035. if (!this._externalData) {
  27036. return null;
  27037. }
  27038. return this._externalData.get(key);
  27039. };
  27040. /**
  27041. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27042. * @param key the unique key that identifies the data
  27043. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27044. * @return the associated data, can be null if the factory returned null.
  27045. */
  27046. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27047. if (!this._externalData) {
  27048. this._externalData = new BABYLON.StringDictionary();
  27049. }
  27050. return this._externalData.getOrAddWithFactory(key, factory);
  27051. };
  27052. /**
  27053. * Remove an externaly attached data from the Engine instance
  27054. * @param key the unique key that identifies the data
  27055. * @return true if the data was successfully removed, false if it doesn't exist
  27056. */
  27057. Scene.prototype.removeExternalData = function (key) {
  27058. return this._externalData.remove(key);
  27059. };
  27060. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27061. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27062. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27063. var step = _a[_i];
  27064. step.action(mesh, subMesh);
  27065. }
  27066. var material = subMesh.getMaterial();
  27067. if (material !== null && material !== undefined) {
  27068. // Render targets
  27069. if (material.getRenderTargetTextures !== undefined) {
  27070. if (this._processedMaterials.indexOf(material) === -1) {
  27071. this._processedMaterials.push(material);
  27072. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27073. }
  27074. }
  27075. // Dispatch
  27076. this._activeIndices.addCount(subMesh.indexCount, false);
  27077. this._renderingManager.dispatch(subMesh, mesh, material);
  27078. }
  27079. }
  27080. };
  27081. /**
  27082. * Clear the processed materials smart array preventing retention point in material dispose.
  27083. */
  27084. Scene.prototype.freeProcessedMaterials = function () {
  27085. this._processedMaterials.dispose();
  27086. };
  27087. /**
  27088. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27089. */
  27090. Scene.prototype.freeActiveMeshes = function () {
  27091. this._activeMeshes.dispose();
  27092. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27093. this.activeCamera._activeMeshes.dispose();
  27094. }
  27095. if (this.activeCameras) {
  27096. for (var i = 0; i < this.activeCameras.length; i++) {
  27097. var activeCamera = this.activeCameras[i];
  27098. if (activeCamera && activeCamera._activeMeshes) {
  27099. activeCamera._activeMeshes.dispose();
  27100. }
  27101. }
  27102. }
  27103. };
  27104. /**
  27105. * Clear the info related to rendering groups preventing retention points during dispose.
  27106. */
  27107. Scene.prototype.freeRenderingGroups = function () {
  27108. if (this._renderingManager) {
  27109. this._renderingManager.freeRenderingGroups();
  27110. }
  27111. if (this.textures) {
  27112. for (var i = 0; i < this.textures.length; i++) {
  27113. var texture = this.textures[i];
  27114. if (texture && texture.renderList) {
  27115. texture.freeRenderingGroups();
  27116. }
  27117. }
  27118. }
  27119. };
  27120. /** @hidden */
  27121. Scene.prototype._isInIntermediateRendering = function () {
  27122. return this._intermediateRendering;
  27123. };
  27124. /**
  27125. * Defines the current active mesh candidate provider
  27126. * @param provider defines the provider to use
  27127. */
  27128. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27129. this._activeMeshCandidateProvider = provider;
  27130. };
  27131. /**
  27132. * Gets the current active mesh candidate provider
  27133. * @returns the current active mesh candidate provider
  27134. */
  27135. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27136. return this._activeMeshCandidateProvider;
  27137. };
  27138. /**
  27139. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27140. * @returns the current scene
  27141. */
  27142. Scene.prototype.freezeActiveMeshes = function () {
  27143. if (!this.activeCamera) {
  27144. return this;
  27145. }
  27146. if (!this._frustumPlanes) {
  27147. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27148. }
  27149. this._evaluateActiveMeshes();
  27150. this._activeMeshesFrozen = true;
  27151. return this;
  27152. };
  27153. /**
  27154. * Use this function to restart evaluating active meshes on every frame
  27155. * @returns the current scene
  27156. */
  27157. Scene.prototype.unfreezeActiveMeshes = function () {
  27158. this._activeMeshesFrozen = false;
  27159. return this;
  27160. };
  27161. Scene.prototype._evaluateActiveMeshes = function () {
  27162. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27163. return;
  27164. }
  27165. if (!this.activeCamera) {
  27166. return;
  27167. }
  27168. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27169. this.activeCamera._activeMeshes.reset();
  27170. this._activeMeshes.reset();
  27171. this._renderingManager.reset();
  27172. this._processedMaterials.reset();
  27173. this._activeParticleSystems.reset();
  27174. this._activeSkeletons.reset();
  27175. this._softwareSkinnedMeshes.reset();
  27176. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27177. var step = _a[_i];
  27178. step.action();
  27179. }
  27180. // Meshes
  27181. var meshes;
  27182. var len;
  27183. var checkIsEnabled = true;
  27184. // Determine mesh candidates
  27185. if (this._activeMeshCandidateProvider !== undefined) {
  27186. // Use _activeMeshCandidateProvider
  27187. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27188. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27189. if (meshes !== undefined) {
  27190. len = meshes.length;
  27191. }
  27192. else {
  27193. len = 0;
  27194. }
  27195. }
  27196. else if (this._selectionOctree !== undefined) {
  27197. // Octree
  27198. var selection = this._selectionOctree.select(this._frustumPlanes);
  27199. meshes = selection.data;
  27200. len = selection.length;
  27201. }
  27202. else {
  27203. // Full scene traversal
  27204. len = this.meshes.length;
  27205. meshes = this.meshes;
  27206. }
  27207. // Check each mesh
  27208. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27209. mesh = meshes[meshIndex];
  27210. if (mesh.isBlocked) {
  27211. continue;
  27212. }
  27213. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27214. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27215. continue;
  27216. }
  27217. mesh.computeWorldMatrix();
  27218. // Intersections
  27219. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27220. this._meshesForIntersections.pushNoDuplicate(mesh);
  27221. }
  27222. // Switch to current LOD
  27223. meshLOD = mesh.getLOD(this.activeCamera);
  27224. if (meshLOD === undefined || meshLOD === null) {
  27225. continue;
  27226. }
  27227. mesh._preActivate();
  27228. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27229. this._activeMeshes.push(mesh);
  27230. this.activeCamera._activeMeshes.push(mesh);
  27231. mesh._activate(this._renderId);
  27232. if (meshLOD !== mesh) {
  27233. meshLOD._activate(this._renderId);
  27234. }
  27235. this._activeMesh(mesh, meshLOD);
  27236. }
  27237. }
  27238. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27239. // Particle systems
  27240. if (this.particlesEnabled) {
  27241. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27242. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27243. var particleSystem = this.particleSystems[particleIndex];
  27244. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27245. continue;
  27246. }
  27247. var emitter = particleSystem.emitter;
  27248. if (!emitter.position || emitter.isEnabled()) {
  27249. this._activeParticleSystems.push(particleSystem);
  27250. particleSystem.animate();
  27251. this._renderingManager.dispatchParticles(particleSystem);
  27252. }
  27253. }
  27254. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27255. }
  27256. };
  27257. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27258. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27259. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27260. mesh.skeleton.prepare();
  27261. }
  27262. if (!mesh.computeBonesUsingShaders) {
  27263. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27264. }
  27265. }
  27266. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27267. var step = _a[_i];
  27268. step.action(sourceMesh, mesh);
  27269. }
  27270. if (mesh !== undefined && mesh !== null
  27271. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27272. // Submeshes Octrees
  27273. var len;
  27274. var subMeshes;
  27275. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27276. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27277. len = intersections.length;
  27278. subMeshes = intersections.data;
  27279. }
  27280. else {
  27281. subMeshes = mesh.subMeshes;
  27282. len = subMeshes.length;
  27283. }
  27284. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27285. subMesh = subMeshes[subIndex];
  27286. this._evaluateSubMesh(subMesh, mesh);
  27287. }
  27288. }
  27289. };
  27290. /**
  27291. * Update the transform matrix to update from the current active camera
  27292. * @param force defines a boolean used to force the update even if cache is up to date
  27293. */
  27294. Scene.prototype.updateTransformMatrix = function (force) {
  27295. if (!this.activeCamera) {
  27296. return;
  27297. }
  27298. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27299. };
  27300. /**
  27301. * 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)
  27302. * @param alternateCamera defines the camera to use
  27303. */
  27304. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27305. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27306. };
  27307. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27308. if (camera && camera._skipRendering) {
  27309. return;
  27310. }
  27311. var engine = this._engine;
  27312. this.activeCamera = camera;
  27313. if (!this.activeCamera)
  27314. throw new Error("Active camera not set");
  27315. // Viewport
  27316. engine.setViewport(this.activeCamera.viewport);
  27317. // Camera
  27318. this.resetCachedMaterial();
  27319. this._renderId++;
  27320. this.updateTransformMatrix();
  27321. if (camera._alternateCamera) {
  27322. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27323. this._alternateRendering = true;
  27324. }
  27325. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27326. // Meshes
  27327. this._evaluateActiveMeshes();
  27328. // Software skinning
  27329. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27330. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27331. mesh.applySkeleton(mesh.skeleton);
  27332. }
  27333. // Render targets
  27334. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27335. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27336. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27337. }
  27338. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27339. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27340. }
  27341. if (this.renderTargetsEnabled) {
  27342. this._intermediateRendering = true;
  27343. if (this._renderTargets.length > 0) {
  27344. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27345. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27346. var renderTarget = this._renderTargets.data[renderIndex];
  27347. if (renderTarget._shouldRender()) {
  27348. this._renderId++;
  27349. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27350. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27351. }
  27352. }
  27353. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27354. this._renderId++;
  27355. }
  27356. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27357. var step = _a[_i];
  27358. step.action(this.activeCamera);
  27359. }
  27360. this._intermediateRendering = false;
  27361. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27362. }
  27363. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27364. // Prepare Frame
  27365. if (this.postProcessManager) {
  27366. this.postProcessManager._prepareFrame();
  27367. }
  27368. // Before Camera Draw
  27369. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27370. var step = _c[_b];
  27371. step.action(this.activeCamera);
  27372. }
  27373. // Render
  27374. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27375. this._renderingManager.render(null, null, true, true);
  27376. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27377. // After Camera Draw
  27378. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27379. var step = _e[_d];
  27380. step.action(this.activeCamera);
  27381. }
  27382. // Finalize frame
  27383. if (this.postProcessManager) {
  27384. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27385. }
  27386. // Reset some special arrays
  27387. this._renderTargets.reset();
  27388. this._alternateRendering = false;
  27389. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27390. };
  27391. Scene.prototype._processSubCameras = function (camera) {
  27392. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27393. this._renderForCamera(camera);
  27394. return;
  27395. }
  27396. // rig cameras
  27397. for (var index = 0; index < camera._rigCameras.length; index++) {
  27398. this._renderForCamera(camera._rigCameras[index], camera);
  27399. }
  27400. this.activeCamera = camera;
  27401. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27402. };
  27403. Scene.prototype._checkIntersections = function () {
  27404. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27405. var sourceMesh = this._meshesForIntersections.data[index];
  27406. if (!sourceMesh.actionManager) {
  27407. continue;
  27408. }
  27409. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27410. var action = sourceMesh.actionManager.actions[actionIndex];
  27411. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27412. var parameters = action.getTriggerParameter();
  27413. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27414. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27415. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27416. if (areIntersecting && currentIntersectionInProgress === -1) {
  27417. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27418. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27419. sourceMesh._intersectionsInProgress.push(otherMesh);
  27420. }
  27421. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27422. sourceMesh._intersectionsInProgress.push(otherMesh);
  27423. }
  27424. }
  27425. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27426. //They intersected, and now they don't.
  27427. //is this trigger an exit trigger? execute an event.
  27428. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27429. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27430. }
  27431. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27432. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27433. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27434. return otherMesh === parameterMesh;
  27435. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27436. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27437. }
  27438. }
  27439. }
  27440. }
  27441. }
  27442. };
  27443. /**
  27444. * Render the scene
  27445. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27446. */
  27447. Scene.prototype.render = function (updateCameras) {
  27448. if (updateCameras === void 0) { updateCameras = true; }
  27449. if (this.isDisposed) {
  27450. return;
  27451. }
  27452. // Register components that have been associated lately to the scene.
  27453. this._registerTransientComponents();
  27454. this._activeParticles.fetchNewFrame();
  27455. this._totalVertices.fetchNewFrame();
  27456. this._activeIndices.fetchNewFrame();
  27457. this._activeBones.fetchNewFrame();
  27458. this._meshesForIntersections.reset();
  27459. this.resetCachedMaterial();
  27460. this.onBeforeAnimationsObservable.notifyObservers(this);
  27461. // Actions
  27462. if (this.actionManager) {
  27463. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27464. }
  27465. //Simplification Queue
  27466. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27467. this.simplificationQueue.executeNext();
  27468. }
  27469. if (this._engine.isDeterministicLockStep()) {
  27470. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27471. var defaultFPS = (60.0 / 1000.0);
  27472. var defaultFrameTime = 1000 / 60; // frame time in MS
  27473. if (this._physicsEngine) {
  27474. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27475. }
  27476. var stepsTaken = 0;
  27477. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27478. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27479. internalSteps = Math.min(internalSteps, maxSubSteps);
  27480. do {
  27481. this.onBeforeStepObservable.notifyObservers(this);
  27482. // Animations
  27483. this._animationRatio = defaultFrameTime * defaultFPS;
  27484. this._animate();
  27485. this.onAfterAnimationsObservable.notifyObservers(this);
  27486. // Physics
  27487. if (this._physicsEngine) {
  27488. this.onBeforePhysicsObservable.notifyObservers(this);
  27489. this._physicsEngine._step(defaultFrameTime / 1000);
  27490. this.onAfterPhysicsObservable.notifyObservers(this);
  27491. }
  27492. this.onAfterStepObservable.notifyObservers(this);
  27493. this._currentStepId++;
  27494. stepsTaken++;
  27495. deltaTime -= defaultFrameTime;
  27496. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27497. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27498. }
  27499. else {
  27500. // Animations
  27501. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27502. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27503. this._animate();
  27504. this.onAfterAnimationsObservable.notifyObservers(this);
  27505. // Physics
  27506. if (this._physicsEngine) {
  27507. this.onBeforePhysicsObservable.notifyObservers(this);
  27508. this._physicsEngine._step(deltaTime / 1000.0);
  27509. this.onAfterPhysicsObservable.notifyObservers(this);
  27510. }
  27511. }
  27512. // Before camera update steps
  27513. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27514. var step = _a[_i];
  27515. step.action();
  27516. }
  27517. // Update Cameras
  27518. if (updateCameras) {
  27519. if (this.activeCameras.length > 0) {
  27520. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27521. var camera = this.activeCameras[cameraIndex];
  27522. camera.update();
  27523. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27524. // rig cameras
  27525. for (var index = 0; index < camera._rigCameras.length; index++) {
  27526. camera._rigCameras[index].update();
  27527. }
  27528. }
  27529. }
  27530. }
  27531. else if (this.activeCamera) {
  27532. this.activeCamera.update();
  27533. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27534. // rig cameras
  27535. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27536. this.activeCamera._rigCameras[index].update();
  27537. }
  27538. }
  27539. }
  27540. }
  27541. // Before render
  27542. this.onBeforeRenderObservable.notifyObservers(this);
  27543. // Customs render targets
  27544. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27545. var engine = this.getEngine();
  27546. var currentActiveCamera = this.activeCamera;
  27547. if (this.renderTargetsEnabled) {
  27548. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27549. this._intermediateRendering = true;
  27550. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27551. var renderTarget = this.customRenderTargets[customIndex];
  27552. if (renderTarget._shouldRender()) {
  27553. this._renderId++;
  27554. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27555. if (!this.activeCamera)
  27556. throw new Error("Active camera not set");
  27557. // Viewport
  27558. engine.setViewport(this.activeCamera.viewport);
  27559. // Camera
  27560. this.updateTransformMatrix();
  27561. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27562. }
  27563. }
  27564. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27565. this._intermediateRendering = false;
  27566. this._renderId++;
  27567. }
  27568. // Restore back buffer
  27569. if (this.customRenderTargets.length > 0) {
  27570. engine.restoreDefaultFramebuffer();
  27571. }
  27572. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27573. this.activeCamera = currentActiveCamera;
  27574. // Procedural textures
  27575. if (this.proceduralTexturesEnabled) {
  27576. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27577. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27578. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27579. if (proceduralTexture._shouldRender()) {
  27580. proceduralTexture.render();
  27581. }
  27582. }
  27583. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27584. }
  27585. // Clear
  27586. if (this.autoClearDepthAndStencil || this.autoClear) {
  27587. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27588. }
  27589. // Shadows
  27590. if (this.shadowsEnabled) {
  27591. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27592. var light = this.lights[lightIndex];
  27593. var shadowGenerator = light.getShadowGenerator();
  27594. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27595. var shadowMap = (shadowGenerator.getShadowMap());
  27596. if (this.textures.indexOf(shadowMap) !== -1) {
  27597. this._renderTargets.push(shadowMap);
  27598. }
  27599. }
  27600. }
  27601. }
  27602. // Depth renderer
  27603. for (var key in this._depthRenderer) {
  27604. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27605. }
  27606. // Geometry renderer
  27607. if (this._geometryBufferRenderer) {
  27608. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27609. }
  27610. // RenderPipeline
  27611. if (this._postProcessRenderPipelineManager) {
  27612. this._postProcessRenderPipelineManager.update();
  27613. }
  27614. // Multi-cameras?
  27615. if (this.activeCameras.length > 0) {
  27616. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27617. if (cameraIndex > 0) {
  27618. this._engine.clear(null, false, true, true);
  27619. }
  27620. this._processSubCameras(this.activeCameras[cameraIndex]);
  27621. }
  27622. }
  27623. else {
  27624. if (!this.activeCamera) {
  27625. throw new Error("No camera defined");
  27626. }
  27627. this._processSubCameras(this.activeCamera);
  27628. }
  27629. // Intersection checks
  27630. this._checkIntersections();
  27631. // Update the audio listener attached to the camera
  27632. if (BABYLON.AudioEngine) {
  27633. this._updateAudioParameters();
  27634. }
  27635. // After render
  27636. if (this.afterRender) {
  27637. this.afterRender();
  27638. }
  27639. this.onAfterRenderObservable.notifyObservers(this);
  27640. // Cleaning
  27641. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27642. var data = this._toBeDisposed.data[index];
  27643. if (data) {
  27644. data.dispose();
  27645. }
  27646. this._toBeDisposed[index] = null;
  27647. }
  27648. this._toBeDisposed.reset();
  27649. if (this.dumpNextRenderTargets) {
  27650. this.dumpNextRenderTargets = false;
  27651. }
  27652. this._activeBones.addCount(0, true);
  27653. this._activeIndices.addCount(0, true);
  27654. this._activeParticles.addCount(0, true);
  27655. };
  27656. Scene.prototype._updateAudioParameters = function () {
  27657. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27658. return;
  27659. }
  27660. var listeningCamera;
  27661. var audioEngine = BABYLON.Engine.audioEngine;
  27662. if (this.activeCameras.length > 0) {
  27663. listeningCamera = this.activeCameras[0];
  27664. }
  27665. else {
  27666. listeningCamera = this.activeCamera;
  27667. }
  27668. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27669. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27670. // for VR cameras
  27671. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27672. listeningCamera = listeningCamera.rigCameras[0];
  27673. }
  27674. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27675. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27676. cameraDirection.normalize();
  27677. // To avoid some errors on GearVR
  27678. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27679. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27680. }
  27681. var i;
  27682. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27683. var sound = this.mainSoundTrack.soundCollection[i];
  27684. if (sound.useCustomAttenuation) {
  27685. sound.updateDistanceFromListener();
  27686. }
  27687. }
  27688. for (i = 0; i < this.soundTracks.length; i++) {
  27689. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27690. sound = this.soundTracks[i].soundCollection[j];
  27691. if (sound.useCustomAttenuation) {
  27692. sound.updateDistanceFromListener();
  27693. }
  27694. }
  27695. }
  27696. }
  27697. };
  27698. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27699. // Audio
  27700. /**
  27701. * Gets or sets if audio support is enabled
  27702. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27703. */
  27704. get: function () {
  27705. return this._audioEnabled;
  27706. },
  27707. set: function (value) {
  27708. this._audioEnabled = value;
  27709. if (BABYLON.AudioEngine) {
  27710. if (this._audioEnabled) {
  27711. this._enableAudio();
  27712. }
  27713. else {
  27714. this._disableAudio();
  27715. }
  27716. }
  27717. },
  27718. enumerable: true,
  27719. configurable: true
  27720. });
  27721. Scene.prototype._disableAudio = function () {
  27722. var i;
  27723. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27724. this.mainSoundTrack.soundCollection[i].pause();
  27725. }
  27726. for (i = 0; i < this.soundTracks.length; i++) {
  27727. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27728. this.soundTracks[i].soundCollection[j].pause();
  27729. }
  27730. }
  27731. };
  27732. Scene.prototype._enableAudio = function () {
  27733. var i;
  27734. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27735. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27736. this.mainSoundTrack.soundCollection[i].play();
  27737. }
  27738. }
  27739. for (i = 0; i < this.soundTracks.length; i++) {
  27740. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27741. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27742. this.soundTracks[i].soundCollection[j].play();
  27743. }
  27744. }
  27745. }
  27746. };
  27747. Object.defineProperty(Scene.prototype, "headphone", {
  27748. /**
  27749. * Gets or sets if audio will be output to headphones
  27750. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27751. */
  27752. get: function () {
  27753. return this._headphone;
  27754. },
  27755. set: function (value) {
  27756. this._headphone = value;
  27757. if (BABYLON.AudioEngine) {
  27758. if (this._headphone) {
  27759. this._switchAudioModeForHeadphones();
  27760. }
  27761. else {
  27762. this._switchAudioModeForNormalSpeakers();
  27763. }
  27764. }
  27765. },
  27766. enumerable: true,
  27767. configurable: true
  27768. });
  27769. Scene.prototype._switchAudioModeForHeadphones = function () {
  27770. this.mainSoundTrack.switchPanningModelToHRTF();
  27771. for (var i = 0; i < this.soundTracks.length; i++) {
  27772. this.soundTracks[i].switchPanningModelToHRTF();
  27773. }
  27774. };
  27775. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27776. this.mainSoundTrack.switchPanningModelToEqualPower();
  27777. for (var i = 0; i < this.soundTracks.length; i++) {
  27778. this.soundTracks[i].switchPanningModelToEqualPower();
  27779. }
  27780. };
  27781. /**
  27782. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27783. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27784. * @returns the created depth renderer
  27785. */
  27786. Scene.prototype.enableDepthRenderer = function (camera) {
  27787. camera = camera || this.activeCamera;
  27788. if (!camera) {
  27789. throw "No camera available to enable depth renderer";
  27790. }
  27791. if (!this._depthRenderer[camera.id]) {
  27792. var textureType = 0;
  27793. if (this._engine.getCaps().textureHalfFloatRender) {
  27794. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27795. }
  27796. else if (this._engine.getCaps().textureFloatRender) {
  27797. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27798. }
  27799. else {
  27800. throw "Depth renderer does not support int texture type";
  27801. }
  27802. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27803. }
  27804. return this._depthRenderer[camera.id];
  27805. };
  27806. /**
  27807. * Disables a depth renderer for a given camera
  27808. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27809. */
  27810. Scene.prototype.disableDepthRenderer = function (camera) {
  27811. camera = camera || this.activeCamera;
  27812. if (!camera || !this._depthRenderer[camera.id]) {
  27813. return;
  27814. }
  27815. this._depthRenderer[camera.id].dispose();
  27816. delete this._depthRenderer[camera.id];
  27817. };
  27818. /**
  27819. * Enables a GeometryBufferRender and associates it with the scene
  27820. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27821. * @returns the GeometryBufferRenderer
  27822. */
  27823. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27824. if (ratio === void 0) { ratio = 1; }
  27825. if (this._geometryBufferRenderer) {
  27826. return this._geometryBufferRenderer;
  27827. }
  27828. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27829. if (!this._geometryBufferRenderer.isSupported) {
  27830. this._geometryBufferRenderer = null;
  27831. }
  27832. return this._geometryBufferRenderer;
  27833. };
  27834. /**
  27835. * Disables the GeometryBufferRender associated with the scene
  27836. */
  27837. Scene.prototype.disableGeometryBufferRenderer = function () {
  27838. if (!this._geometryBufferRenderer) {
  27839. return;
  27840. }
  27841. this._geometryBufferRenderer.dispose();
  27842. this._geometryBufferRenderer = null;
  27843. };
  27844. /**
  27845. * Freeze all materials
  27846. * A frozen material will not be updatable but should be faster to render
  27847. */
  27848. Scene.prototype.freezeMaterials = function () {
  27849. for (var i = 0; i < this.materials.length; i++) {
  27850. this.materials[i].freeze();
  27851. }
  27852. };
  27853. /**
  27854. * Unfreeze all materials
  27855. * A frozen material will not be updatable but should be faster to render
  27856. */
  27857. Scene.prototype.unfreezeMaterials = function () {
  27858. for (var i = 0; i < this.materials.length; i++) {
  27859. this.materials[i].unfreeze();
  27860. }
  27861. };
  27862. /**
  27863. * Releases all held ressources
  27864. */
  27865. Scene.prototype.dispose = function () {
  27866. this.beforeRender = null;
  27867. this.afterRender = null;
  27868. this.skeletons = [];
  27869. this.morphTargetManagers = [];
  27870. this._transientComponents = [];
  27871. this._isReadyForMeshStage.clear();
  27872. this._beforeEvaluateActiveMeshStage.clear();
  27873. this._evaluateSubMeshStage.clear();
  27874. this._activeMeshStage.clear();
  27875. this._cameraDrawRenderTargetStage.clear();
  27876. this._beforeCameraDrawStage.clear();
  27877. this._beforeRenderingGroupDrawStage.clear();
  27878. this._afterRenderingGroupDrawStage.clear();
  27879. this._afterCameraDrawStage.clear();
  27880. this._beforeCameraUpdateStage.clear();
  27881. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27882. var component = _a[_i];
  27883. component.dispose();
  27884. }
  27885. this.importedMeshesFiles = new Array();
  27886. this.stopAllAnimations();
  27887. this.resetCachedMaterial();
  27888. for (var key in this._depthRenderer) {
  27889. this._depthRenderer[key].dispose();
  27890. }
  27891. // Smart arrays
  27892. if (this.activeCamera) {
  27893. this.activeCamera._activeMeshes.dispose();
  27894. this.activeCamera = null;
  27895. }
  27896. this._activeMeshes.dispose();
  27897. this._renderingManager.dispose();
  27898. this._processedMaterials.dispose();
  27899. this._activeParticleSystems.dispose();
  27900. this._activeSkeletons.dispose();
  27901. this._softwareSkinnedMeshes.dispose();
  27902. this._renderTargets.dispose();
  27903. this._registeredForLateAnimationBindings.dispose();
  27904. this._meshesForIntersections.dispose();
  27905. this._toBeDisposed.dispose();
  27906. // Abort active requests
  27907. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27908. var request = _c[_b];
  27909. request.abort();
  27910. }
  27911. // Debug layer
  27912. if (this._debugLayer) {
  27913. this._debugLayer.hide();
  27914. }
  27915. // Events
  27916. this.onDisposeObservable.notifyObservers(this);
  27917. this.onDisposeObservable.clear();
  27918. this.onBeforeRenderObservable.clear();
  27919. this.onAfterRenderObservable.clear();
  27920. this.onBeforeRenderTargetsRenderObservable.clear();
  27921. this.onAfterRenderTargetsRenderObservable.clear();
  27922. this.onAfterStepObservable.clear();
  27923. this.onBeforeStepObservable.clear();
  27924. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27925. this.onAfterActiveMeshesEvaluationObservable.clear();
  27926. this.onBeforeParticlesRenderingObservable.clear();
  27927. this.onAfterParticlesRenderingObservable.clear();
  27928. this.onBeforeSpritesRenderingObservable.clear();
  27929. this.onAfterSpritesRenderingObservable.clear();
  27930. this.onBeforeDrawPhaseObservable.clear();
  27931. this.onAfterDrawPhaseObservable.clear();
  27932. this.onBeforePhysicsObservable.clear();
  27933. this.onAfterPhysicsObservable.clear();
  27934. this.onBeforeAnimationsObservable.clear();
  27935. this.onAfterAnimationsObservable.clear();
  27936. this.onDataLoadedObservable.clear();
  27937. this.onBeforeRenderingGroupObservable.clear();
  27938. this.onAfterRenderingGroupObservable.clear();
  27939. this.detachControl();
  27940. // Release sounds & sounds tracks
  27941. if (BABYLON.AudioEngine) {
  27942. this.disposeSounds();
  27943. }
  27944. // VR Helper
  27945. if (this.VRHelper) {
  27946. this.VRHelper.dispose();
  27947. }
  27948. // Detach cameras
  27949. var canvas = this._engine.getRenderingCanvas();
  27950. if (canvas) {
  27951. var index;
  27952. for (index = 0; index < this.cameras.length; index++) {
  27953. this.cameras[index].detachControl(canvas);
  27954. }
  27955. }
  27956. // Release animation groups
  27957. while (this.animationGroups.length) {
  27958. this.animationGroups[0].dispose();
  27959. }
  27960. // Release lights
  27961. while (this.lights.length) {
  27962. this.lights[0].dispose();
  27963. }
  27964. // Release meshes
  27965. while (this.meshes.length) {
  27966. this.meshes[0].dispose(true);
  27967. }
  27968. while (this.transformNodes.length) {
  27969. this.removeTransformNode(this.transformNodes[0]);
  27970. }
  27971. // Release cameras
  27972. while (this.cameras.length) {
  27973. this.cameras[0].dispose();
  27974. }
  27975. // Release materials
  27976. if (this.defaultMaterial) {
  27977. this.defaultMaterial.dispose();
  27978. }
  27979. while (this.multiMaterials.length) {
  27980. this.multiMaterials[0].dispose();
  27981. }
  27982. while (this.materials.length) {
  27983. this.materials[0].dispose();
  27984. }
  27985. // Release particles
  27986. while (this.particleSystems.length) {
  27987. this.particleSystems[0].dispose();
  27988. }
  27989. // Release sprites
  27990. while (this.spriteManagers.length) {
  27991. this.spriteManagers[0].dispose();
  27992. }
  27993. // Release postProcesses
  27994. while (this.postProcesses.length) {
  27995. this.postProcesses[0].dispose();
  27996. }
  27997. // Release textures
  27998. while (this.textures.length) {
  27999. this.textures[0].dispose();
  28000. }
  28001. // Release UBO
  28002. this._sceneUbo.dispose();
  28003. if (this._alternateSceneUbo) {
  28004. this._alternateSceneUbo.dispose();
  28005. }
  28006. // Post-processes
  28007. this.postProcessManager.dispose();
  28008. if (this._postProcessRenderPipelineManager) {
  28009. this._postProcessRenderPipelineManager.dispose();
  28010. }
  28011. // Physics
  28012. if (this._physicsEngine) {
  28013. this.disablePhysicsEngine();
  28014. }
  28015. // Remove from engine
  28016. index = this._engine.scenes.indexOf(this);
  28017. if (index > -1) {
  28018. this._engine.scenes.splice(index, 1);
  28019. }
  28020. this._engine.wipeCaches(true);
  28021. this._isDisposed = true;
  28022. };
  28023. Object.defineProperty(Scene.prototype, "isDisposed", {
  28024. /**
  28025. * Gets if the scene is already disposed
  28026. */
  28027. get: function () {
  28028. return this._isDisposed;
  28029. },
  28030. enumerable: true,
  28031. configurable: true
  28032. });
  28033. /**
  28034. * Releases sounds & soundtracks
  28035. */
  28036. Scene.prototype.disposeSounds = function () {
  28037. if (!this._mainSoundTrack) {
  28038. return;
  28039. }
  28040. this.mainSoundTrack.dispose();
  28041. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28042. this.soundTracks[scIndex].dispose();
  28043. }
  28044. };
  28045. /**
  28046. * Call this function to reduce memory footprint of the scene.
  28047. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28048. */
  28049. Scene.prototype.clearCachedVertexData = function () {
  28050. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28051. var mesh = this.meshes[meshIndex];
  28052. var geometry = mesh.geometry;
  28053. if (geometry) {
  28054. geometry._indices = [];
  28055. for (var vbName in geometry._vertexBuffers) {
  28056. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28057. continue;
  28058. }
  28059. geometry._vertexBuffers[vbName]._buffer._data = null;
  28060. }
  28061. }
  28062. }
  28063. };
  28064. /**
  28065. * This function will remove the local cached buffer data from texture.
  28066. * It will save memory but will prevent the texture from being rebuilt
  28067. */
  28068. Scene.prototype.cleanCachedTextureBuffer = function () {
  28069. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28070. var baseTexture = _a[_i];
  28071. var buffer = baseTexture._buffer;
  28072. if (buffer) {
  28073. baseTexture._buffer = null;
  28074. }
  28075. }
  28076. };
  28077. // Octrees
  28078. /**
  28079. * Get the world extend vectors with an optional filter
  28080. *
  28081. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28082. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28083. */
  28084. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28085. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28086. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28087. filterPredicate = filterPredicate || (function () { return true; });
  28088. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28089. mesh.computeWorldMatrix(true);
  28090. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28091. return;
  28092. }
  28093. var boundingInfo = mesh.getBoundingInfo();
  28094. var minBox = boundingInfo.boundingBox.minimumWorld;
  28095. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28096. BABYLON.Tools.CheckExtends(minBox, min, max);
  28097. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28098. });
  28099. return {
  28100. min: min,
  28101. max: max
  28102. };
  28103. };
  28104. /**
  28105. * Creates or updates the octree used to boost selection (picking)
  28106. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28107. * @param maxCapacity defines the maximum capacity per leaf
  28108. * @param maxDepth defines the maximum depth of the octree
  28109. * @returns an octree of AbstractMesh
  28110. */
  28111. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28112. if (maxCapacity === void 0) { maxCapacity = 64; }
  28113. if (maxDepth === void 0) { maxDepth = 2; }
  28114. if (!this._selectionOctree) {
  28115. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28116. }
  28117. var worldExtends = this.getWorldExtends();
  28118. // Update octree
  28119. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28120. return this._selectionOctree;
  28121. };
  28122. // Picking
  28123. /**
  28124. * Creates a ray that can be used to pick in the scene
  28125. * @param x defines the x coordinate of the origin (on-screen)
  28126. * @param y defines the y coordinate of the origin (on-screen)
  28127. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28128. * @param camera defines the camera to use for the picking
  28129. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28130. * @returns a Ray
  28131. */
  28132. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28133. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28134. var result = BABYLON.Ray.Zero();
  28135. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28136. return result;
  28137. };
  28138. /**
  28139. * Creates a ray that can be used to pick in the scene
  28140. * @param x defines the x coordinate of the origin (on-screen)
  28141. * @param y defines the y coordinate of the origin (on-screen)
  28142. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28143. * @param result defines the ray where to store the picking ray
  28144. * @param camera defines the camera to use for the picking
  28145. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28146. * @returns the current scene
  28147. */
  28148. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28149. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28150. var engine = this._engine;
  28151. if (!camera) {
  28152. if (!this.activeCamera)
  28153. throw new Error("Active camera not set");
  28154. camera = this.activeCamera;
  28155. }
  28156. var cameraViewport = camera.viewport;
  28157. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28158. // Moving coordinates to local viewport world
  28159. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28160. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28161. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28162. return this;
  28163. };
  28164. /**
  28165. * Creates a ray that can be used to pick in the scene
  28166. * @param x defines the x coordinate of the origin (on-screen)
  28167. * @param y defines the y coordinate of the origin (on-screen)
  28168. * @param camera defines the camera to use for the picking
  28169. * @returns a Ray
  28170. */
  28171. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28172. var result = BABYLON.Ray.Zero();
  28173. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28174. return result;
  28175. };
  28176. /**
  28177. * Creates a ray that can be used to pick in the scene
  28178. * @param x defines the x coordinate of the origin (on-screen)
  28179. * @param y defines the y coordinate of the origin (on-screen)
  28180. * @param result defines the ray where to store the picking ray
  28181. * @param camera defines the camera to use for the picking
  28182. * @returns the current scene
  28183. */
  28184. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28185. if (!BABYLON.PickingInfo) {
  28186. return this;
  28187. }
  28188. var engine = this._engine;
  28189. if (!camera) {
  28190. if (!this.activeCamera)
  28191. throw new Error("Active camera not set");
  28192. camera = this.activeCamera;
  28193. }
  28194. var cameraViewport = camera.viewport;
  28195. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28196. var identity = BABYLON.Matrix.Identity();
  28197. // Moving coordinates to local viewport world
  28198. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28199. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28200. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28201. return this;
  28202. };
  28203. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28204. if (!BABYLON.PickingInfo) {
  28205. return null;
  28206. }
  28207. var pickingInfo = null;
  28208. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28209. var mesh = this.meshes[meshIndex];
  28210. if (predicate) {
  28211. if (!predicate(mesh)) {
  28212. continue;
  28213. }
  28214. }
  28215. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28216. continue;
  28217. }
  28218. var world = mesh.getWorldMatrix();
  28219. var ray = rayFunction(world);
  28220. var result = mesh.intersects(ray, fastCheck);
  28221. if (!result || !result.hit)
  28222. continue;
  28223. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28224. continue;
  28225. pickingInfo = result;
  28226. if (fastCheck) {
  28227. break;
  28228. }
  28229. }
  28230. return pickingInfo || new BABYLON.PickingInfo();
  28231. };
  28232. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28233. if (!BABYLON.PickingInfo) {
  28234. return null;
  28235. }
  28236. var pickingInfos = new Array();
  28237. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28238. var mesh = this.meshes[meshIndex];
  28239. if (predicate) {
  28240. if (!predicate(mesh)) {
  28241. continue;
  28242. }
  28243. }
  28244. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28245. continue;
  28246. }
  28247. var world = mesh.getWorldMatrix();
  28248. var ray = rayFunction(world);
  28249. var result = mesh.intersects(ray, false);
  28250. if (!result || !result.hit)
  28251. continue;
  28252. pickingInfos.push(result);
  28253. }
  28254. return pickingInfos;
  28255. };
  28256. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28257. if (!BABYLON.PickingInfo) {
  28258. return null;
  28259. }
  28260. var pickingInfo = null;
  28261. if (!camera) {
  28262. if (!this.activeCamera) {
  28263. return null;
  28264. }
  28265. camera = this.activeCamera;
  28266. }
  28267. if (this.spriteManagers.length > 0) {
  28268. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28269. var spriteManager = this.spriteManagers[spriteIndex];
  28270. if (!spriteManager.isPickable) {
  28271. continue;
  28272. }
  28273. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28274. if (!result || !result.hit)
  28275. continue;
  28276. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28277. continue;
  28278. pickingInfo = result;
  28279. if (fastCheck) {
  28280. break;
  28281. }
  28282. }
  28283. }
  28284. return pickingInfo || new BABYLON.PickingInfo();
  28285. };
  28286. /** Launch a ray to try to pick a mesh in the scene
  28287. * @param x position on screen
  28288. * @param y position on screen
  28289. * @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
  28290. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28291. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28292. * @returns a PickingInfo
  28293. */
  28294. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28295. var _this = this;
  28296. if (!BABYLON.PickingInfo) {
  28297. return null;
  28298. }
  28299. var result = this._internalPick(function (world) {
  28300. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28301. return _this._tempPickingRay;
  28302. }, predicate, fastCheck);
  28303. if (result) {
  28304. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28305. }
  28306. return result;
  28307. };
  28308. /** Launch a ray to try to pick a sprite in the scene
  28309. * @param x position on screen
  28310. * @param y position on screen
  28311. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28312. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28313. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28314. * @returns a PickingInfo
  28315. */
  28316. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28317. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28318. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28319. };
  28320. /** Use the given ray to pick a mesh in the scene
  28321. * @param ray The ray to use to pick meshes
  28322. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28323. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28324. * @returns a PickingInfo
  28325. */
  28326. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28327. var _this = this;
  28328. var result = this._internalPick(function (world) {
  28329. if (!_this._pickWithRayInverseMatrix) {
  28330. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28331. }
  28332. world.invertToRef(_this._pickWithRayInverseMatrix);
  28333. if (!_this._cachedRayForTransform) {
  28334. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28335. }
  28336. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28337. return _this._cachedRayForTransform;
  28338. }, predicate, fastCheck);
  28339. if (result) {
  28340. result.ray = ray;
  28341. }
  28342. return result;
  28343. };
  28344. /**
  28345. * Launch a ray to try to pick a mesh in the scene
  28346. * @param x X position on screen
  28347. * @param y Y position on screen
  28348. * @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
  28349. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28350. * @returns an array of PickingInfo
  28351. */
  28352. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28353. var _this = this;
  28354. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28355. };
  28356. /**
  28357. * Launch a ray to try to pick a mesh in the scene
  28358. * @param ray Ray to use
  28359. * @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
  28360. * @returns an array of PickingInfo
  28361. */
  28362. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28363. var _this = this;
  28364. return this._internalMultiPick(function (world) {
  28365. if (!_this._pickWithRayInverseMatrix) {
  28366. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28367. }
  28368. world.invertToRef(_this._pickWithRayInverseMatrix);
  28369. if (!_this._cachedRayForTransform) {
  28370. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28371. }
  28372. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28373. return _this._cachedRayForTransform;
  28374. }, predicate);
  28375. };
  28376. /**
  28377. * Force the value of meshUnderPointer
  28378. * @param mesh defines the mesh to use
  28379. */
  28380. Scene.prototype.setPointerOverMesh = function (mesh) {
  28381. if (this._pointerOverMesh === mesh) {
  28382. return;
  28383. }
  28384. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28385. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28386. }
  28387. this._pointerOverMesh = mesh;
  28388. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28389. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28390. }
  28391. };
  28392. /**
  28393. * Gets the mesh under the pointer
  28394. * @returns a Mesh or null if no mesh is under the pointer
  28395. */
  28396. Scene.prototype.getPointerOverMesh = function () {
  28397. return this._pointerOverMesh;
  28398. };
  28399. /**
  28400. * Force the sprite under the pointer
  28401. * @param sprite defines the sprite to use
  28402. */
  28403. Scene.prototype.setPointerOverSprite = function (sprite) {
  28404. if (this._pointerOverSprite === sprite) {
  28405. return;
  28406. }
  28407. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28408. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28409. }
  28410. this._pointerOverSprite = sprite;
  28411. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28412. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28413. }
  28414. };
  28415. /**
  28416. * Gets the sprite under the pointer
  28417. * @returns a Sprite or null if no sprite is under the pointer
  28418. */
  28419. Scene.prototype.getPointerOverSprite = function () {
  28420. return this._pointerOverSprite;
  28421. };
  28422. // Physics
  28423. /**
  28424. * Gets the current physics engine
  28425. * @returns a PhysicsEngine or null if none attached
  28426. */
  28427. Scene.prototype.getPhysicsEngine = function () {
  28428. return this._physicsEngine;
  28429. };
  28430. /**
  28431. * Enables physics to the current scene
  28432. * @param gravity defines the scene's gravity for the physics engine
  28433. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28434. * @return a boolean indicating if the physics engine was initialized
  28435. */
  28436. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28437. if (gravity === void 0) { gravity = null; }
  28438. if (this._physicsEngine) {
  28439. return true;
  28440. }
  28441. try {
  28442. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28443. return true;
  28444. }
  28445. catch (e) {
  28446. BABYLON.Tools.Error(e.message);
  28447. return false;
  28448. }
  28449. };
  28450. /**
  28451. * Disables and disposes the physics engine associated with the scene
  28452. */
  28453. Scene.prototype.disablePhysicsEngine = function () {
  28454. if (!this._physicsEngine) {
  28455. return;
  28456. }
  28457. this._physicsEngine.dispose();
  28458. this._physicsEngine = null;
  28459. };
  28460. /**
  28461. * Gets a boolean indicating if there is an active physics engine
  28462. * @returns a boolean indicating if there is an active physics engine
  28463. */
  28464. Scene.prototype.isPhysicsEnabled = function () {
  28465. return this._physicsEngine !== undefined;
  28466. };
  28467. /**
  28468. * Deletes a physics compound impostor
  28469. * @param compound defines the compound to delete
  28470. */
  28471. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28472. var mesh = compound.parts[0].mesh;
  28473. if (mesh.physicsImpostor) {
  28474. mesh.physicsImpostor.dispose( /*true*/);
  28475. mesh.physicsImpostor = null;
  28476. }
  28477. };
  28478. // Misc.
  28479. /** @hidden */
  28480. Scene.prototype._rebuildGeometries = function () {
  28481. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28482. var geometry = _a[_i];
  28483. geometry._rebuild();
  28484. }
  28485. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28486. var mesh = _c[_b];
  28487. mesh._rebuild();
  28488. }
  28489. if (this.postProcessManager) {
  28490. this.postProcessManager._rebuild();
  28491. }
  28492. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28493. var component = _e[_d];
  28494. component.rebuild();
  28495. }
  28496. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28497. var system = _g[_f];
  28498. system.rebuild();
  28499. }
  28500. if (this._postProcessRenderPipelineManager) {
  28501. this._postProcessRenderPipelineManager._rebuild();
  28502. }
  28503. };
  28504. /** @hidden */
  28505. Scene.prototype._rebuildTextures = function () {
  28506. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28507. var texture = _a[_i];
  28508. texture._rebuild();
  28509. }
  28510. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28511. };
  28512. /**
  28513. * Creates a default light for the scene.
  28514. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28515. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28516. */
  28517. Scene.prototype.createDefaultLight = function (replace) {
  28518. if (replace === void 0) { replace = false; }
  28519. // Dispose existing light in replace mode.
  28520. if (replace) {
  28521. if (this.lights) {
  28522. for (var i = 0; i < this.lights.length; i++) {
  28523. this.lights[i].dispose();
  28524. }
  28525. }
  28526. }
  28527. // Light
  28528. if (this.lights.length === 0) {
  28529. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28530. }
  28531. };
  28532. /**
  28533. * Creates a default camera for the scene.
  28534. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28535. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28536. * @param replace has default false, when true replaces the active camera in the scene
  28537. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28538. */
  28539. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28540. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28541. if (replace === void 0) { replace = false; }
  28542. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28543. // Dispose existing camera in replace mode.
  28544. if (replace) {
  28545. if (this.activeCamera) {
  28546. this.activeCamera.dispose();
  28547. this.activeCamera = null;
  28548. }
  28549. }
  28550. // Camera
  28551. if (!this.activeCamera) {
  28552. var worldExtends = this.getWorldExtends();
  28553. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28554. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28555. var camera;
  28556. var radius = worldSize.length() * 1.5;
  28557. // empty scene scenario!
  28558. if (!isFinite(radius)) {
  28559. radius = 1;
  28560. worldCenter.copyFromFloats(0, 0, 0);
  28561. }
  28562. if (createArcRotateCamera) {
  28563. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28564. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28565. arcRotateCamera.wheelPrecision = 100 / radius;
  28566. camera = arcRotateCamera;
  28567. }
  28568. else {
  28569. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28570. freeCamera.setTarget(worldCenter);
  28571. camera = freeCamera;
  28572. }
  28573. camera.minZ = radius * 0.01;
  28574. camera.maxZ = radius * 1000;
  28575. camera.speed = radius * 0.2;
  28576. this.activeCamera = camera;
  28577. var canvas = this.getEngine().getRenderingCanvas();
  28578. if (attachCameraControls && canvas) {
  28579. camera.attachControl(canvas);
  28580. }
  28581. }
  28582. };
  28583. /**
  28584. * Creates a default camera and a default light.
  28585. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28586. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28587. * @param replace has the default false, when true replaces the active camera/light in the scene
  28588. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28589. */
  28590. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28591. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28592. if (replace === void 0) { replace = false; }
  28593. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28594. this.createDefaultLight(replace);
  28595. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28596. };
  28597. /**
  28598. * Creates a new sky box
  28599. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28600. * @param environmentTexture defines the texture to use as environment texture
  28601. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28602. * @param scale defines the overall scale of the skybox
  28603. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28604. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28605. * @returns a new mesh holding the sky box
  28606. */
  28607. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28608. if (pbr === void 0) { pbr = false; }
  28609. if (scale === void 0) { scale = 1000; }
  28610. if (blur === void 0) { blur = 0; }
  28611. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28612. if (!environmentTexture) {
  28613. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28614. return null;
  28615. }
  28616. if (setGlobalEnvTexture) {
  28617. if (environmentTexture) {
  28618. this.environmentTexture = environmentTexture;
  28619. }
  28620. }
  28621. // Skybox
  28622. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28623. if (pbr) {
  28624. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28625. hdrSkyboxMaterial.backFaceCulling = false;
  28626. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28627. if (hdrSkyboxMaterial.reflectionTexture) {
  28628. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28629. }
  28630. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28631. hdrSkyboxMaterial.disableLighting = true;
  28632. hdrSkyboxMaterial.twoSidedLighting = true;
  28633. hdrSkybox.infiniteDistance = true;
  28634. hdrSkybox.material = hdrSkyboxMaterial;
  28635. }
  28636. else {
  28637. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28638. skyboxMaterial.backFaceCulling = false;
  28639. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28640. if (skyboxMaterial.reflectionTexture) {
  28641. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28642. }
  28643. skyboxMaterial.disableLighting = true;
  28644. hdrSkybox.infiniteDistance = true;
  28645. hdrSkybox.material = skyboxMaterial;
  28646. }
  28647. return hdrSkybox;
  28648. };
  28649. /**
  28650. * Creates a new environment
  28651. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28652. * @param options defines the options you can use to configure the environment
  28653. * @returns the new EnvironmentHelper
  28654. */
  28655. Scene.prototype.createDefaultEnvironment = function (options) {
  28656. if (BABYLON.EnvironmentHelper) {
  28657. return new BABYLON.EnvironmentHelper(options, this);
  28658. }
  28659. return null;
  28660. };
  28661. /**
  28662. * Creates a new VREXperienceHelper
  28663. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28664. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28665. * @returns a new VREXperienceHelper
  28666. */
  28667. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28668. if (webVROptions === void 0) { webVROptions = {}; }
  28669. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28670. };
  28671. // Tags
  28672. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28673. if (tagsQuery === undefined) {
  28674. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28675. return list;
  28676. }
  28677. var listByTags = [];
  28678. forEach = forEach || (function (item) { return; });
  28679. for (var i in list) {
  28680. var item = list[i];
  28681. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28682. listByTags.push(item);
  28683. forEach(item);
  28684. }
  28685. }
  28686. return listByTags;
  28687. };
  28688. /**
  28689. * Get a list of meshes by tags
  28690. * @param tagsQuery defines the tags query to use
  28691. * @param forEach defines a predicate used to filter results
  28692. * @returns an array of Mesh
  28693. */
  28694. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28695. return this._getByTags(this.meshes, tagsQuery, forEach);
  28696. };
  28697. /**
  28698. * Get a list of cameras by tags
  28699. * @param tagsQuery defines the tags query to use
  28700. * @param forEach defines a predicate used to filter results
  28701. * @returns an array of Camera
  28702. */
  28703. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28704. return this._getByTags(this.cameras, tagsQuery, forEach);
  28705. };
  28706. /**
  28707. * Get a list of lights by tags
  28708. * @param tagsQuery defines the tags query to use
  28709. * @param forEach defines a predicate used to filter results
  28710. * @returns an array of Light
  28711. */
  28712. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28713. return this._getByTags(this.lights, tagsQuery, forEach);
  28714. };
  28715. /**
  28716. * Get a list of materials by tags
  28717. * @param tagsQuery defines the tags query to use
  28718. * @param forEach defines a predicate used to filter results
  28719. * @returns an array of Material
  28720. */
  28721. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28722. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28723. };
  28724. /**
  28725. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28726. * This allowed control for front to back rendering or reversly depending of the special needs.
  28727. *
  28728. * @param renderingGroupId The rendering group id corresponding to its index
  28729. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28730. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28731. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28732. */
  28733. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28734. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28735. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28736. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28737. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28738. };
  28739. /**
  28740. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28741. *
  28742. * @param renderingGroupId The rendering group id corresponding to its index
  28743. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28744. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28745. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28746. */
  28747. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28748. if (depth === void 0) { depth = true; }
  28749. if (stencil === void 0) { stencil = true; }
  28750. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28751. };
  28752. /**
  28753. * Gets the current auto clear configuration for one rendering group of the rendering
  28754. * manager.
  28755. * @param index the rendering group index to get the information for
  28756. * @returns The auto clear setup for the requested rendering group
  28757. */
  28758. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28759. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28760. };
  28761. /**
  28762. * Will flag all materials as dirty to trigger new shader compilation
  28763. * @param flag defines the flag used to specify which material part must be marked as dirty
  28764. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28765. */
  28766. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28767. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28768. var material = _a[_i];
  28769. if (predicate && !predicate(material)) {
  28770. continue;
  28771. }
  28772. material.markAsDirty(flag);
  28773. }
  28774. };
  28775. /** @hidden */
  28776. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28777. var _this = this;
  28778. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28779. this._activeRequests.push(request);
  28780. request.onCompleteObservable.add(function (request) {
  28781. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28782. });
  28783. return request;
  28784. };
  28785. /** @hidden */
  28786. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28787. var _this = this;
  28788. return new Promise(function (resolve, reject) {
  28789. _this._loadFile(url, function (data) {
  28790. resolve(data);
  28791. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28792. reject(exception);
  28793. });
  28794. });
  28795. };
  28796. // Statics
  28797. Scene._FOGMODE_NONE = 0;
  28798. Scene._FOGMODE_EXP = 1;
  28799. Scene._FOGMODE_EXP2 = 2;
  28800. Scene._FOGMODE_LINEAR = 3;
  28801. Scene._uniqueIdCounter = 0;
  28802. /**
  28803. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28804. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28805. */
  28806. Scene.MinDeltaTime = 1.0;
  28807. /**
  28808. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28809. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28810. */
  28811. Scene.MaxDeltaTime = 1000.0;
  28812. /** The distance in pixel that you have to move to prevent some events */
  28813. Scene.DragMovementThreshold = 10; // in pixels
  28814. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28815. Scene.LongPressDelay = 500; // in milliseconds
  28816. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28817. Scene.DoubleClickDelay = 300; // in milliseconds
  28818. /** If you need to check double click without raising a single click at first click, enable this flag */
  28819. Scene.ExclusiveDoubleClickMode = false;
  28820. return Scene;
  28821. }(BABYLON.AbstractScene));
  28822. BABYLON.Scene = Scene;
  28823. })(BABYLON || (BABYLON = {}));
  28824. //# sourceMappingURL=babylon.scene.js.map
  28825. var BABYLON;
  28826. (function (BABYLON) {
  28827. /**
  28828. * Set of assets to keep when moving a scene into an asset container.
  28829. */
  28830. var KeepAssets = /** @class */ (function (_super) {
  28831. __extends(KeepAssets, _super);
  28832. function KeepAssets() {
  28833. return _super !== null && _super.apply(this, arguments) || this;
  28834. }
  28835. return KeepAssets;
  28836. }(BABYLON.AbstractScene));
  28837. BABYLON.KeepAssets = KeepAssets;
  28838. /**
  28839. * Container with a set of assets that can be added or removed from a scene.
  28840. */
  28841. var AssetContainer = /** @class */ (function (_super) {
  28842. __extends(AssetContainer, _super);
  28843. /**
  28844. * Instantiates an AssetContainer.
  28845. * @param scene The scene the AssetContainer belongs to.
  28846. */
  28847. function AssetContainer(scene) {
  28848. var _this = _super.call(this) || this;
  28849. _this.scene = scene;
  28850. return _this;
  28851. }
  28852. /**
  28853. * Adds all the assets from the container to the scene.
  28854. */
  28855. AssetContainer.prototype.addAllToScene = function () {
  28856. var _this = this;
  28857. this.cameras.forEach(function (o) {
  28858. _this.scene.addCamera(o);
  28859. });
  28860. this.lights.forEach(function (o) {
  28861. _this.scene.addLight(o);
  28862. });
  28863. this.meshes.forEach(function (o) {
  28864. _this.scene.addMesh(o);
  28865. });
  28866. this.skeletons.forEach(function (o) {
  28867. _this.scene.addSkeleton(o);
  28868. });
  28869. this.animations.forEach(function (o) {
  28870. _this.scene.addAnimation(o);
  28871. });
  28872. this.animationGroups.forEach(function (o) {
  28873. _this.scene.addAnimationGroup(o);
  28874. });
  28875. this.multiMaterials.forEach(function (o) {
  28876. _this.scene.addMultiMaterial(o);
  28877. });
  28878. this.materials.forEach(function (o) {
  28879. _this.scene.addMaterial(o);
  28880. });
  28881. this.morphTargetManagers.forEach(function (o) {
  28882. _this.scene.addMorphTargetManager(o);
  28883. });
  28884. this.geometries.forEach(function (o) {
  28885. _this.scene.addGeometry(o);
  28886. });
  28887. this.transformNodes.forEach(function (o) {
  28888. _this.scene.addTransformNode(o);
  28889. });
  28890. this.actionManagers.forEach(function (o) {
  28891. _this.scene.addActionManager(o);
  28892. });
  28893. this.sounds.forEach(function (o) {
  28894. o.play();
  28895. o.autoplay = true;
  28896. _this.scene.mainSoundTrack.AddSound(o);
  28897. });
  28898. this.textures.forEach(function (o) {
  28899. _this.scene.addTexture(o);
  28900. });
  28901. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28902. var component = _a[_i];
  28903. component.addFromContainer(this.scene);
  28904. }
  28905. };
  28906. /**
  28907. * Removes all the assets in the container from the scene
  28908. */
  28909. AssetContainer.prototype.removeAllFromScene = function () {
  28910. var _this = this;
  28911. this.cameras.forEach(function (o) {
  28912. _this.scene.removeCamera(o);
  28913. });
  28914. this.lights.forEach(function (o) {
  28915. _this.scene.removeLight(o);
  28916. });
  28917. this.meshes.forEach(function (o) {
  28918. _this.scene.removeMesh(o);
  28919. });
  28920. this.skeletons.forEach(function (o) {
  28921. _this.scene.removeSkeleton(o);
  28922. });
  28923. this.animations.forEach(function (o) {
  28924. _this.scene.removeAnimation(o);
  28925. });
  28926. this.animationGroups.forEach(function (o) {
  28927. _this.scene.removeAnimationGroup(o);
  28928. });
  28929. this.multiMaterials.forEach(function (o) {
  28930. _this.scene.removeMultiMaterial(o);
  28931. });
  28932. this.materials.forEach(function (o) {
  28933. _this.scene.removeMaterial(o);
  28934. });
  28935. this.morphTargetManagers.forEach(function (o) {
  28936. _this.scene.removeMorphTargetManager(o);
  28937. });
  28938. this.geometries.forEach(function (o) {
  28939. _this.scene.removeGeometry(o);
  28940. });
  28941. this.transformNodes.forEach(function (o) {
  28942. _this.scene.removeTransformNode(o);
  28943. });
  28944. this.actionManagers.forEach(function (o) {
  28945. _this.scene.removeActionManager(o);
  28946. });
  28947. this.sounds.forEach(function (o) {
  28948. o.stop();
  28949. o.autoplay = false;
  28950. _this.scene.mainSoundTrack.RemoveSound(o);
  28951. });
  28952. this.textures.forEach(function (o) {
  28953. _this.scene.removeTexture(o);
  28954. });
  28955. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28956. var component = _a[_i];
  28957. component.removeFromContainer(this.scene);
  28958. }
  28959. };
  28960. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28961. if (!sourceAssets) {
  28962. return;
  28963. }
  28964. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28965. var asset = sourceAssets_1[_i];
  28966. var move = true;
  28967. if (keepAssets) {
  28968. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28969. var keepAsset = keepAssets_1[_a];
  28970. if (asset === keepAsset) {
  28971. move = false;
  28972. break;
  28973. }
  28974. }
  28975. }
  28976. if (move) {
  28977. targetAssets.push(asset);
  28978. }
  28979. }
  28980. };
  28981. /**
  28982. * Removes all the assets contained in the scene and adds them to the container.
  28983. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28984. */
  28985. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28986. if (keepAssets === undefined) {
  28987. keepAssets = new KeepAssets();
  28988. }
  28989. for (var key in this) {
  28990. if (this.hasOwnProperty(key)) {
  28991. this[key] = this[key] || [];
  28992. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28993. }
  28994. }
  28995. this.removeAllFromScene();
  28996. };
  28997. /**
  28998. * 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.
  28999. * @returns the root mesh
  29000. */
  29001. AssetContainer.prototype.createRootMesh = function () {
  29002. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29003. this.meshes.forEach(function (m) {
  29004. if (!m.parent) {
  29005. rootMesh.addChild(m);
  29006. }
  29007. });
  29008. this.meshes.unshift(rootMesh);
  29009. return rootMesh;
  29010. };
  29011. return AssetContainer;
  29012. }(BABYLON.AbstractScene));
  29013. BABYLON.AssetContainer = AssetContainer;
  29014. })(BABYLON || (BABYLON = {}));
  29015. //# sourceMappingURL=babylon.assetContainer.js.map
  29016. var BABYLON;
  29017. (function (BABYLON) {
  29018. var Buffer = /** @class */ (function () {
  29019. /**
  29020. * Constructor
  29021. * @param engine the engine
  29022. * @param data the data to use for this buffer
  29023. * @param updatable whether the data is updatable
  29024. * @param stride the stride (optional)
  29025. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29026. * @param instanced whether the buffer is instanced (optional)
  29027. * @param useBytes set to true if the stride in in bytes (optional)
  29028. */
  29029. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29030. if (stride === void 0) { stride = 0; }
  29031. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29032. if (instanced === void 0) { instanced = false; }
  29033. if (useBytes === void 0) { useBytes = false; }
  29034. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29035. this._engine = engine.getScene().getEngine();
  29036. }
  29037. else {
  29038. this._engine = engine;
  29039. }
  29040. this._updatable = updatable;
  29041. this._instanced = instanced;
  29042. this._data = data;
  29043. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29044. if (!postponeInternalCreation) { // by default
  29045. this.create();
  29046. }
  29047. }
  29048. /**
  29049. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29050. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29051. * @param offset defines offset in the buffer (0 by default)
  29052. * @param size defines the size in floats of attributes (position is 3 for instance)
  29053. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29054. * @param instanced defines if the vertex buffer contains indexed data
  29055. * @param useBytes defines if the offset and stride are in bytes
  29056. * @returns the new vertex buffer
  29057. */
  29058. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29059. if (useBytes === void 0) { useBytes = false; }
  29060. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29061. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29062. // a lot of these parameters are ignored as they are overriden by the buffer
  29063. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29064. };
  29065. // Properties
  29066. Buffer.prototype.isUpdatable = function () {
  29067. return this._updatable;
  29068. };
  29069. Buffer.prototype.getData = function () {
  29070. return this._data;
  29071. };
  29072. Buffer.prototype.getBuffer = function () {
  29073. return this._buffer;
  29074. };
  29075. /**
  29076. * Gets the stride in float32 units (i.e. byte stride / 4).
  29077. * May not be an integer if the byte stride is not divisible by 4.
  29078. * DEPRECATED. Use byteStride instead.
  29079. * @returns the stride in float32 units
  29080. */
  29081. Buffer.prototype.getStrideSize = function () {
  29082. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29083. };
  29084. // Methods
  29085. Buffer.prototype.create = function (data) {
  29086. if (data === void 0) { data = null; }
  29087. if (!data && this._buffer) {
  29088. return; // nothing to do
  29089. }
  29090. data = data || this._data;
  29091. if (!data) {
  29092. return;
  29093. }
  29094. if (!this._buffer) { // create buffer
  29095. if (this._updatable) {
  29096. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29097. this._data = data;
  29098. }
  29099. else {
  29100. this._buffer = this._engine.createVertexBuffer(data);
  29101. }
  29102. }
  29103. else if (this._updatable) { // update buffer
  29104. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29105. this._data = data;
  29106. }
  29107. };
  29108. Buffer.prototype._rebuild = function () {
  29109. this._buffer = null;
  29110. this.create(this._data);
  29111. };
  29112. Buffer.prototype.update = function (data) {
  29113. this.create(data);
  29114. };
  29115. /**
  29116. * Updates the data directly.
  29117. * @param data the new data
  29118. * @param offset the new offset
  29119. * @param vertexCount the vertex count (optional)
  29120. * @param useBytes set to true if the offset is in bytes
  29121. */
  29122. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29123. if (useBytes === void 0) { useBytes = false; }
  29124. if (!this._buffer) {
  29125. return;
  29126. }
  29127. if (this._updatable) { // update buffer
  29128. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29129. this._data = null;
  29130. }
  29131. };
  29132. Buffer.prototype.dispose = function () {
  29133. if (!this._buffer) {
  29134. return;
  29135. }
  29136. if (this._engine._releaseBuffer(this._buffer)) {
  29137. this._buffer = null;
  29138. }
  29139. };
  29140. return Buffer;
  29141. }());
  29142. BABYLON.Buffer = Buffer;
  29143. })(BABYLON || (BABYLON = {}));
  29144. //# sourceMappingURL=babylon.buffer.js.map
  29145. var BABYLON;
  29146. (function (BABYLON) {
  29147. var VertexBuffer = /** @class */ (function () {
  29148. /**
  29149. * Constructor
  29150. * @param engine the engine
  29151. * @param data the data to use for this vertex buffer
  29152. * @param kind the vertex buffer kind
  29153. * @param updatable whether the data is updatable
  29154. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29155. * @param stride the stride (optional)
  29156. * @param instanced whether the buffer is instanced (optional)
  29157. * @param offset the offset of the data (optional)
  29158. * @param size the number of components (optional)
  29159. * @param type the type of the component (optional)
  29160. * @param normalized whether the data contains normalized data (optional)
  29161. * @param useBytes set to true if stride and offset are in bytes (optional)
  29162. */
  29163. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29164. if (normalized === void 0) { normalized = false; }
  29165. if (useBytes === void 0) { useBytes = false; }
  29166. if (data instanceof BABYLON.Buffer) {
  29167. this._buffer = data;
  29168. this._ownsBuffer = false;
  29169. }
  29170. else {
  29171. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29172. this._ownsBuffer = true;
  29173. }
  29174. this._kind = kind;
  29175. if (type == undefined) {
  29176. var data_1 = this.getData();
  29177. this.type = VertexBuffer.FLOAT;
  29178. if (data_1 instanceof Int8Array)
  29179. this.type = VertexBuffer.BYTE;
  29180. else if (data_1 instanceof Uint8Array)
  29181. this.type = VertexBuffer.UNSIGNED_BYTE;
  29182. else if (data_1 instanceof Int16Array)
  29183. this.type = VertexBuffer.SHORT;
  29184. else if (data_1 instanceof Uint16Array)
  29185. this.type = VertexBuffer.UNSIGNED_SHORT;
  29186. else if (data_1 instanceof Int32Array)
  29187. this.type = VertexBuffer.INT;
  29188. else if (data_1 instanceof Uint32Array)
  29189. this.type = VertexBuffer.UNSIGNED_INT;
  29190. }
  29191. else {
  29192. this.type = type;
  29193. }
  29194. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29195. if (useBytes) {
  29196. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29197. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29198. this.byteOffset = offset || 0;
  29199. }
  29200. else {
  29201. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29202. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29203. this.byteOffset = (offset || 0) * typeByteLength;
  29204. }
  29205. this.normalized = normalized;
  29206. this._instanced = instanced !== undefined ? instanced : false;
  29207. this._instanceDivisor = instanced ? 1 : 0;
  29208. }
  29209. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29210. /**
  29211. * Gets or sets the instance divisor when in instanced mode
  29212. */
  29213. get: function () {
  29214. return this._instanceDivisor;
  29215. },
  29216. set: function (value) {
  29217. this._instanceDivisor = value;
  29218. if (value == 0) {
  29219. this._instanced = false;
  29220. }
  29221. else {
  29222. this._instanced = true;
  29223. }
  29224. },
  29225. enumerable: true,
  29226. configurable: true
  29227. });
  29228. VertexBuffer.prototype._rebuild = function () {
  29229. if (!this._buffer) {
  29230. return;
  29231. }
  29232. this._buffer._rebuild();
  29233. };
  29234. /**
  29235. * Returns the kind of the VertexBuffer (string).
  29236. */
  29237. VertexBuffer.prototype.getKind = function () {
  29238. return this._kind;
  29239. };
  29240. // Properties
  29241. /**
  29242. * Boolean : is the VertexBuffer updatable ?
  29243. */
  29244. VertexBuffer.prototype.isUpdatable = function () {
  29245. return this._buffer.isUpdatable();
  29246. };
  29247. /**
  29248. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29249. */
  29250. VertexBuffer.prototype.getData = function () {
  29251. return this._buffer.getData();
  29252. };
  29253. /**
  29254. * Returns the WebGLBuffer associated to the VertexBuffer.
  29255. */
  29256. VertexBuffer.prototype.getBuffer = function () {
  29257. return this._buffer.getBuffer();
  29258. };
  29259. /**
  29260. * Returns the stride as a multiple of the type byte length.
  29261. * DEPRECATED. Use byteStride instead.
  29262. */
  29263. VertexBuffer.prototype.getStrideSize = function () {
  29264. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29265. };
  29266. /**
  29267. * Returns the offset as a multiple of the type byte length.
  29268. * DEPRECATED. Use byteOffset instead.
  29269. */
  29270. VertexBuffer.prototype.getOffset = function () {
  29271. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29272. };
  29273. /**
  29274. * Returns the number of components per vertex attribute (integer).
  29275. */
  29276. VertexBuffer.prototype.getSize = function () {
  29277. return this._size;
  29278. };
  29279. /**
  29280. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29281. */
  29282. VertexBuffer.prototype.getIsInstanced = function () {
  29283. return this._instanced;
  29284. };
  29285. /**
  29286. * Returns the instancing divisor, zero for non-instanced (integer).
  29287. */
  29288. VertexBuffer.prototype.getInstanceDivisor = function () {
  29289. return this._instanceDivisor;
  29290. };
  29291. // Methods
  29292. /**
  29293. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29294. * Returns the created WebGLBuffer.
  29295. */
  29296. VertexBuffer.prototype.create = function (data) {
  29297. return this._buffer.create(data);
  29298. };
  29299. /**
  29300. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29301. * This function will create a new buffer if the current one is not updatable
  29302. * Returns the updated WebGLBuffer.
  29303. */
  29304. VertexBuffer.prototype.update = function (data) {
  29305. return this._buffer.update(data);
  29306. };
  29307. /**
  29308. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29309. * Returns the directly updated WebGLBuffer.
  29310. * @param data the new data
  29311. * @param offset the new offset
  29312. * @param useBytes set to true if the offset is in bytes
  29313. */
  29314. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29315. if (useBytes === void 0) { useBytes = false; }
  29316. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29317. };
  29318. /**
  29319. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29320. */
  29321. VertexBuffer.prototype.dispose = function () {
  29322. if (this._ownsBuffer) {
  29323. this._buffer.dispose();
  29324. }
  29325. };
  29326. /**
  29327. * Enumerates each value of this vertex buffer as numbers.
  29328. * @param count the number of values to enumerate
  29329. * @param callback the callback function called for each value
  29330. */
  29331. VertexBuffer.prototype.forEach = function (count, callback) {
  29332. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29333. };
  29334. Object.defineProperty(VertexBuffer, "PositionKind", {
  29335. get: function () {
  29336. return VertexBuffer._PositionKind;
  29337. },
  29338. enumerable: true,
  29339. configurable: true
  29340. });
  29341. Object.defineProperty(VertexBuffer, "NormalKind", {
  29342. get: function () {
  29343. return VertexBuffer._NormalKind;
  29344. },
  29345. enumerable: true,
  29346. configurable: true
  29347. });
  29348. Object.defineProperty(VertexBuffer, "TangentKind", {
  29349. get: function () {
  29350. return VertexBuffer._TangentKind;
  29351. },
  29352. enumerable: true,
  29353. configurable: true
  29354. });
  29355. Object.defineProperty(VertexBuffer, "UVKind", {
  29356. get: function () {
  29357. return VertexBuffer._UVKind;
  29358. },
  29359. enumerable: true,
  29360. configurable: true
  29361. });
  29362. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29363. get: function () {
  29364. return VertexBuffer._UV2Kind;
  29365. },
  29366. enumerable: true,
  29367. configurable: true
  29368. });
  29369. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29370. get: function () {
  29371. return VertexBuffer._UV3Kind;
  29372. },
  29373. enumerable: true,
  29374. configurable: true
  29375. });
  29376. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29377. get: function () {
  29378. return VertexBuffer._UV4Kind;
  29379. },
  29380. enumerable: true,
  29381. configurable: true
  29382. });
  29383. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29384. get: function () {
  29385. return VertexBuffer._UV5Kind;
  29386. },
  29387. enumerable: true,
  29388. configurable: true
  29389. });
  29390. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29391. get: function () {
  29392. return VertexBuffer._UV6Kind;
  29393. },
  29394. enumerable: true,
  29395. configurable: true
  29396. });
  29397. Object.defineProperty(VertexBuffer, "ColorKind", {
  29398. get: function () {
  29399. return VertexBuffer._ColorKind;
  29400. },
  29401. enumerable: true,
  29402. configurable: true
  29403. });
  29404. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29405. get: function () {
  29406. return VertexBuffer._MatricesIndicesKind;
  29407. },
  29408. enumerable: true,
  29409. configurable: true
  29410. });
  29411. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29412. get: function () {
  29413. return VertexBuffer._MatricesWeightsKind;
  29414. },
  29415. enumerable: true,
  29416. configurable: true
  29417. });
  29418. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29419. get: function () {
  29420. return VertexBuffer._MatricesIndicesExtraKind;
  29421. },
  29422. enumerable: true,
  29423. configurable: true
  29424. });
  29425. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29426. get: function () {
  29427. return VertexBuffer._MatricesWeightsExtraKind;
  29428. },
  29429. enumerable: true,
  29430. configurable: true
  29431. });
  29432. /**
  29433. * Deduces the stride given a kind.
  29434. * @param kind The kind string to deduce
  29435. * @returns The deduced stride
  29436. */
  29437. VertexBuffer.DeduceStride = function (kind) {
  29438. switch (kind) {
  29439. case VertexBuffer.UVKind:
  29440. case VertexBuffer.UV2Kind:
  29441. case VertexBuffer.UV3Kind:
  29442. case VertexBuffer.UV4Kind:
  29443. case VertexBuffer.UV5Kind:
  29444. case VertexBuffer.UV6Kind:
  29445. return 2;
  29446. case VertexBuffer.NormalKind:
  29447. case VertexBuffer.PositionKind:
  29448. return 3;
  29449. case VertexBuffer.ColorKind:
  29450. case VertexBuffer.MatricesIndicesKind:
  29451. case VertexBuffer.MatricesIndicesExtraKind:
  29452. case VertexBuffer.MatricesWeightsKind:
  29453. case VertexBuffer.MatricesWeightsExtraKind:
  29454. case VertexBuffer.TangentKind:
  29455. return 4;
  29456. default:
  29457. throw new Error("Invalid kind '" + kind + "'");
  29458. }
  29459. };
  29460. /**
  29461. * Gets the byte length of the given type.
  29462. * @param type the type
  29463. * @returns the number of bytes
  29464. */
  29465. VertexBuffer.GetTypeByteLength = function (type) {
  29466. switch (type) {
  29467. case VertexBuffer.BYTE:
  29468. case VertexBuffer.UNSIGNED_BYTE:
  29469. return 1;
  29470. case VertexBuffer.SHORT:
  29471. case VertexBuffer.UNSIGNED_SHORT:
  29472. return 2;
  29473. case VertexBuffer.INT:
  29474. case VertexBuffer.FLOAT:
  29475. return 4;
  29476. default:
  29477. throw new Error("Invalid type '" + type + "'");
  29478. }
  29479. };
  29480. /**
  29481. * Enumerates each value of the given parameters as numbers.
  29482. * @param data the data to enumerate
  29483. * @param byteOffset the byte offset of the data
  29484. * @param byteStride the byte stride of the data
  29485. * @param componentCount the number of components per element
  29486. * @param componentType the type of the component
  29487. * @param count the total number of components
  29488. * @param normalized whether the data is normalized
  29489. * @param callback the callback function called for each value
  29490. */
  29491. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29492. if (data instanceof Array) {
  29493. var offset = byteOffset / 4;
  29494. var stride = byteStride / 4;
  29495. for (var index = 0; index < count; index += componentCount) {
  29496. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29497. callback(data[offset + componentIndex], index + componentIndex);
  29498. }
  29499. offset += stride;
  29500. }
  29501. }
  29502. else {
  29503. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29504. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29505. for (var index = 0; index < count; index += componentCount) {
  29506. var componentByteOffset = byteOffset;
  29507. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29508. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29509. callback(value, index + componentIndex);
  29510. componentByteOffset += componentByteLength;
  29511. }
  29512. byteOffset += byteStride;
  29513. }
  29514. }
  29515. };
  29516. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29517. switch (type) {
  29518. case VertexBuffer.BYTE: {
  29519. var value = dataView.getInt8(byteOffset);
  29520. if (normalized) {
  29521. value = Math.max(value / 127, -1);
  29522. }
  29523. return value;
  29524. }
  29525. case VertexBuffer.UNSIGNED_BYTE: {
  29526. var value = dataView.getUint8(byteOffset);
  29527. if (normalized) {
  29528. value = value / 255;
  29529. }
  29530. return value;
  29531. }
  29532. case VertexBuffer.SHORT: {
  29533. var value = dataView.getInt16(byteOffset, true);
  29534. if (normalized) {
  29535. value = Math.max(value / 16383, -1);
  29536. }
  29537. return value;
  29538. }
  29539. case VertexBuffer.UNSIGNED_SHORT: {
  29540. var value = dataView.getUint16(byteOffset, true);
  29541. if (normalized) {
  29542. value = value / 65535;
  29543. }
  29544. return value;
  29545. }
  29546. case VertexBuffer.FLOAT: {
  29547. return dataView.getFloat32(byteOffset, true);
  29548. }
  29549. default: {
  29550. throw new Error("Invalid component type " + type);
  29551. }
  29552. }
  29553. };
  29554. /**
  29555. * The byte type.
  29556. */
  29557. VertexBuffer.BYTE = 5120;
  29558. /**
  29559. * The unsigned byte type.
  29560. */
  29561. VertexBuffer.UNSIGNED_BYTE = 5121;
  29562. /**
  29563. * The short type.
  29564. */
  29565. VertexBuffer.SHORT = 5122;
  29566. /**
  29567. * The unsigned short type.
  29568. */
  29569. VertexBuffer.UNSIGNED_SHORT = 5123;
  29570. /**
  29571. * The integer type.
  29572. */
  29573. VertexBuffer.INT = 5124;
  29574. /**
  29575. * The unsigned integer type.
  29576. */
  29577. VertexBuffer.UNSIGNED_INT = 5125;
  29578. /**
  29579. * The float type.
  29580. */
  29581. VertexBuffer.FLOAT = 5126;
  29582. // Enums
  29583. VertexBuffer._PositionKind = "position";
  29584. VertexBuffer._NormalKind = "normal";
  29585. VertexBuffer._TangentKind = "tangent";
  29586. VertexBuffer._UVKind = "uv";
  29587. VertexBuffer._UV2Kind = "uv2";
  29588. VertexBuffer._UV3Kind = "uv3";
  29589. VertexBuffer._UV4Kind = "uv4";
  29590. VertexBuffer._UV5Kind = "uv5";
  29591. VertexBuffer._UV6Kind = "uv6";
  29592. VertexBuffer._ColorKind = "color";
  29593. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29594. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29595. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29596. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29597. return VertexBuffer;
  29598. }());
  29599. BABYLON.VertexBuffer = VertexBuffer;
  29600. })(BABYLON || (BABYLON = {}));
  29601. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29602. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29603. var BABYLON;
  29604. (function (BABYLON) {
  29605. /**
  29606. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29607. */
  29608. var DummyInternalTextureTracker = /** @class */ (function () {
  29609. function DummyInternalTextureTracker() {
  29610. /**
  29611. * Gets or set the previous tracker in the list
  29612. */
  29613. this.previous = null;
  29614. /**
  29615. * Gets or set the next tracker in the list
  29616. */
  29617. this.next = null;
  29618. }
  29619. return DummyInternalTextureTracker;
  29620. }());
  29621. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29622. })(BABYLON || (BABYLON = {}));
  29623. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29624. var BABYLON;
  29625. (function (BABYLON) {
  29626. /**
  29627. * Class used to store data associated with WebGL texture data for the engine
  29628. * This class should not be used directly
  29629. */
  29630. var InternalTexture = /** @class */ (function () {
  29631. /**
  29632. * Creates a new InternalTexture
  29633. * @param engine defines the engine to use
  29634. * @param dataSource defines the type of data that will be used
  29635. */
  29636. function InternalTexture(engine, dataSource) {
  29637. /**
  29638. * Observable called when the texture is loaded
  29639. */
  29640. this.onLoadedObservable = new BABYLON.Observable();
  29641. /**
  29642. * Gets or set the previous tracker in the list
  29643. */
  29644. this.previous = null;
  29645. /**
  29646. * Gets or set the next tracker in the list
  29647. */
  29648. this.next = null;
  29649. // Private
  29650. /** @hidden */
  29651. this._initialSlot = -1;
  29652. /** @hidden */
  29653. this._designatedSlot = -1;
  29654. /** @hidden */
  29655. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29656. /** @hidden */
  29657. this._comparisonFunction = 0;
  29658. /** @hidden */
  29659. this._sphericalPolynomial = null;
  29660. /** @hidden */
  29661. this._lodGenerationScale = 0;
  29662. /** @hidden */
  29663. this._lodGenerationOffset = 0;
  29664. /** @hidden */
  29665. this._isRGBD = false;
  29666. /** @hidden */
  29667. this._references = 1;
  29668. this._engine = engine;
  29669. this._dataSource = dataSource;
  29670. this._webGLTexture = engine._createTexture();
  29671. }
  29672. /**
  29673. * Gets the Engine the texture belongs to.
  29674. * @returns The babylon engine
  29675. */
  29676. InternalTexture.prototype.getEngine = function () {
  29677. return this._engine;
  29678. };
  29679. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29680. /**
  29681. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29682. */
  29683. get: function () {
  29684. return this._dataSource;
  29685. },
  29686. enumerable: true,
  29687. configurable: true
  29688. });
  29689. /**
  29690. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29691. */
  29692. InternalTexture.prototype.incrementReferences = function () {
  29693. this._references++;
  29694. };
  29695. /**
  29696. * Change the size of the texture (not the size of the content)
  29697. * @param width defines the new width
  29698. * @param height defines the new height
  29699. * @param depth defines the new depth (1 by default)
  29700. */
  29701. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29702. if (depth === void 0) { depth = 1; }
  29703. this.width = width;
  29704. this.height = height;
  29705. this.depth = depth;
  29706. this.baseWidth = width;
  29707. this.baseHeight = height;
  29708. this.baseDepth = depth;
  29709. this._size = width * height * depth;
  29710. };
  29711. /** @hidden */
  29712. InternalTexture.prototype._rebuild = function () {
  29713. var _this = this;
  29714. var proxy;
  29715. this.isReady = false;
  29716. this._cachedCoordinatesMode = null;
  29717. this._cachedWrapU = null;
  29718. this._cachedWrapV = null;
  29719. this._cachedAnisotropicFilteringLevel = null;
  29720. switch (this._dataSource) {
  29721. case InternalTexture.DATASOURCE_TEMP:
  29722. return;
  29723. case InternalTexture.DATASOURCE_URL:
  29724. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29725. _this.isReady = true;
  29726. }, null, this._buffer, undefined, this.format);
  29727. proxy._swapAndDie(this);
  29728. return;
  29729. case InternalTexture.DATASOURCE_RAW:
  29730. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29731. proxy._swapAndDie(this);
  29732. this.isReady = true;
  29733. return;
  29734. case InternalTexture.DATASOURCE_RAW3D:
  29735. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29736. proxy._swapAndDie(this);
  29737. this.isReady = true;
  29738. return;
  29739. case InternalTexture.DATASOURCE_DYNAMIC:
  29740. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29741. proxy._swapAndDie(this);
  29742. // The engine will make sure to update content so no need to flag it as isReady = true
  29743. return;
  29744. case InternalTexture.DATASOURCE_RENDERTARGET:
  29745. var options = new BABYLON.RenderTargetCreationOptions();
  29746. options.generateDepthBuffer = this._generateDepthBuffer;
  29747. options.generateMipMaps = this.generateMipMaps;
  29748. options.generateStencilBuffer = this._generateStencilBuffer;
  29749. options.samplingMode = this.samplingMode;
  29750. options.type = this.type;
  29751. if (this.isCube) {
  29752. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29753. }
  29754. else {
  29755. var size = {
  29756. width: this.width,
  29757. height: this.height
  29758. };
  29759. proxy = this._engine.createRenderTargetTexture(size, options);
  29760. }
  29761. proxy._swapAndDie(this);
  29762. this.isReady = true;
  29763. return;
  29764. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29765. var depthTextureOptions = {
  29766. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29767. comparisonFunction: this._comparisonFunction,
  29768. generateStencil: this._generateStencilBuffer,
  29769. isCube: this.isCube
  29770. };
  29771. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29772. proxy._swapAndDie(this);
  29773. this.isReady = true;
  29774. return;
  29775. case InternalTexture.DATASOURCE_CUBE:
  29776. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29777. _this.isReady = true;
  29778. }, null, this.format, this._extension);
  29779. proxy._swapAndDie(this);
  29780. return;
  29781. case InternalTexture.DATASOURCE_CUBERAW:
  29782. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29783. proxy._swapAndDie(this);
  29784. this.isReady = true;
  29785. return;
  29786. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29787. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29788. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29789. _this.isReady = true;
  29790. });
  29791. proxy._swapAndDie(this);
  29792. return;
  29793. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29794. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29795. if (proxy) {
  29796. proxy._swapAndDie(_this);
  29797. }
  29798. _this.isReady = true;
  29799. }, null, this.format, this._extension);
  29800. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29801. return;
  29802. }
  29803. };
  29804. InternalTexture.prototype._swapAndDie = function (target) {
  29805. target._webGLTexture = this._webGLTexture;
  29806. if (this._framebuffer) {
  29807. target._framebuffer = this._framebuffer;
  29808. }
  29809. if (this._depthStencilBuffer) {
  29810. target._depthStencilBuffer = this._depthStencilBuffer;
  29811. }
  29812. if (this._lodTextureHigh) {
  29813. if (target._lodTextureHigh) {
  29814. target._lodTextureHigh.dispose();
  29815. }
  29816. target._lodTextureHigh = this._lodTextureHigh;
  29817. }
  29818. if (this._lodTextureMid) {
  29819. if (target._lodTextureMid) {
  29820. target._lodTextureMid.dispose();
  29821. }
  29822. target._lodTextureMid = this._lodTextureMid;
  29823. }
  29824. if (this._lodTextureLow) {
  29825. if (target._lodTextureLow) {
  29826. target._lodTextureLow.dispose();
  29827. }
  29828. target._lodTextureLow = this._lodTextureLow;
  29829. }
  29830. var cache = this._engine.getLoadedTexturesCache();
  29831. var index = cache.indexOf(this);
  29832. if (index !== -1) {
  29833. cache.splice(index, 1);
  29834. }
  29835. };
  29836. /**
  29837. * Dispose the current allocated resources
  29838. */
  29839. InternalTexture.prototype.dispose = function () {
  29840. if (!this._webGLTexture) {
  29841. return;
  29842. }
  29843. this._references--;
  29844. if (this._references === 0) {
  29845. this._engine._releaseTexture(this);
  29846. this._webGLTexture = null;
  29847. this.previous = null;
  29848. this.next = null;
  29849. }
  29850. };
  29851. /**
  29852. * The source of the texture data is unknown
  29853. */
  29854. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29855. /**
  29856. * Texture data comes from an URL
  29857. */
  29858. InternalTexture.DATASOURCE_URL = 1;
  29859. /**
  29860. * Texture data is only used for temporary storage
  29861. */
  29862. InternalTexture.DATASOURCE_TEMP = 2;
  29863. /**
  29864. * Texture data comes from raw data (ArrayBuffer)
  29865. */
  29866. InternalTexture.DATASOURCE_RAW = 3;
  29867. /**
  29868. * Texture content is dynamic (video or dynamic texture)
  29869. */
  29870. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29871. /**
  29872. * Texture content is generated by rendering to it
  29873. */
  29874. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29875. /**
  29876. * Texture content is part of a multi render target process
  29877. */
  29878. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29879. /**
  29880. * Texture data comes from a cube data file
  29881. */
  29882. InternalTexture.DATASOURCE_CUBE = 7;
  29883. /**
  29884. * Texture data comes from a raw cube data
  29885. */
  29886. InternalTexture.DATASOURCE_CUBERAW = 8;
  29887. /**
  29888. * Texture data come from a prefiltered cube data file
  29889. */
  29890. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29891. /**
  29892. * Texture content is raw 3D data
  29893. */
  29894. InternalTexture.DATASOURCE_RAW3D = 10;
  29895. /**
  29896. * Texture content is a depth texture
  29897. */
  29898. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29899. /**
  29900. * Texture data comes from a raw cube data encoded with RGBD
  29901. */
  29902. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29903. return InternalTexture;
  29904. }());
  29905. BABYLON.InternalTexture = InternalTexture;
  29906. })(BABYLON || (BABYLON = {}));
  29907. //# sourceMappingURL=babylon.internalTexture.js.map
  29908. var BABYLON;
  29909. (function (BABYLON) {
  29910. var BaseTexture = /** @class */ (function () {
  29911. function BaseTexture(scene) {
  29912. this._hasAlpha = false;
  29913. this.getAlphaFromRGB = false;
  29914. this.level = 1;
  29915. this.coordinatesIndex = 0;
  29916. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29917. /**
  29918. * | Value | Type | Description |
  29919. * | ----- | ------------------ | ----------- |
  29920. * | 0 | CLAMP_ADDRESSMODE | |
  29921. * | 1 | WRAP_ADDRESSMODE | |
  29922. * | 2 | MIRROR_ADDRESSMODE | |
  29923. */
  29924. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29925. /**
  29926. * | Value | Type | Description |
  29927. * | ----- | ------------------ | ----------- |
  29928. * | 0 | CLAMP_ADDRESSMODE | |
  29929. * | 1 | WRAP_ADDRESSMODE | |
  29930. * | 2 | MIRROR_ADDRESSMODE | |
  29931. */
  29932. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29933. /**
  29934. * | Value | Type | Description |
  29935. * | ----- | ------------------ | ----------- |
  29936. * | 0 | CLAMP_ADDRESSMODE | |
  29937. * | 1 | WRAP_ADDRESSMODE | |
  29938. * | 2 | MIRROR_ADDRESSMODE | |
  29939. */
  29940. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29941. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29942. this.isCube = false;
  29943. this.is3D = false;
  29944. this.gammaSpace = true;
  29945. this.invertZ = false;
  29946. this.lodLevelInAlpha = false;
  29947. this.isRenderTarget = false;
  29948. this.animations = new Array();
  29949. /**
  29950. * An event triggered when the texture is disposed.
  29951. */
  29952. this.onDisposeObservable = new BABYLON.Observable();
  29953. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29954. this._cachedSize = BABYLON.Size.Zero();
  29955. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29956. if (this._scene) {
  29957. this._scene.textures.push(this);
  29958. }
  29959. this._uid = null;
  29960. }
  29961. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29962. get: function () {
  29963. return this._hasAlpha;
  29964. },
  29965. set: function (value) {
  29966. if (this._hasAlpha === value) {
  29967. return;
  29968. }
  29969. this._hasAlpha = value;
  29970. if (this._scene) {
  29971. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29972. }
  29973. },
  29974. enumerable: true,
  29975. configurable: true
  29976. });
  29977. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29978. get: function () {
  29979. return this._coordinatesMode;
  29980. },
  29981. /**
  29982. * How a texture is mapped.
  29983. *
  29984. * | Value | Type | Description |
  29985. * | ----- | ----------------------------------- | ----------- |
  29986. * | 0 | EXPLICIT_MODE | |
  29987. * | 1 | SPHERICAL_MODE | |
  29988. * | 2 | PLANAR_MODE | |
  29989. * | 3 | CUBIC_MODE | |
  29990. * | 4 | PROJECTION_MODE | |
  29991. * | 5 | SKYBOX_MODE | |
  29992. * | 6 | INVCUBIC_MODE | |
  29993. * | 7 | EQUIRECTANGULAR_MODE | |
  29994. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29995. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29996. */
  29997. set: function (value) {
  29998. if (this._coordinatesMode === value) {
  29999. return;
  30000. }
  30001. this._coordinatesMode = value;
  30002. if (this._scene) {
  30003. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30004. }
  30005. },
  30006. enumerable: true,
  30007. configurable: true
  30008. });
  30009. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30010. /**
  30011. * Gets whether or not the texture contains RGBD data.
  30012. */
  30013. get: function () {
  30014. return this._texture != null && this._texture._isRGBD;
  30015. },
  30016. enumerable: true,
  30017. configurable: true
  30018. });
  30019. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30020. get: function () {
  30021. if (this._texture)
  30022. return this._texture._lodGenerationOffset;
  30023. return 0.0;
  30024. },
  30025. set: function (value) {
  30026. if (this._texture)
  30027. this._texture._lodGenerationOffset = value;
  30028. },
  30029. enumerable: true,
  30030. configurable: true
  30031. });
  30032. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30033. get: function () {
  30034. if (this._texture)
  30035. return this._texture._lodGenerationScale;
  30036. return 0.0;
  30037. },
  30038. set: function (value) {
  30039. if (this._texture)
  30040. this._texture._lodGenerationScale = value;
  30041. },
  30042. enumerable: true,
  30043. configurable: true
  30044. });
  30045. Object.defineProperty(BaseTexture.prototype, "uid", {
  30046. get: function () {
  30047. if (!this._uid) {
  30048. this._uid = BABYLON.Tools.RandomId();
  30049. }
  30050. return this._uid;
  30051. },
  30052. enumerable: true,
  30053. configurable: true
  30054. });
  30055. BaseTexture.prototype.toString = function () {
  30056. return this.name;
  30057. };
  30058. BaseTexture.prototype.getClassName = function () {
  30059. return "BaseTexture";
  30060. };
  30061. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30062. set: function (callback) {
  30063. if (this._onDisposeObserver) {
  30064. this.onDisposeObservable.remove(this._onDisposeObserver);
  30065. }
  30066. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30067. },
  30068. enumerable: true,
  30069. configurable: true
  30070. });
  30071. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30072. get: function () {
  30073. return true;
  30074. },
  30075. enumerable: true,
  30076. configurable: true
  30077. });
  30078. BaseTexture.prototype.getScene = function () {
  30079. return this._scene;
  30080. };
  30081. BaseTexture.prototype.getTextureMatrix = function () {
  30082. return BABYLON.Matrix.IdentityReadOnly;
  30083. };
  30084. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30085. return BABYLON.Matrix.IdentityReadOnly;
  30086. };
  30087. BaseTexture.prototype.getInternalTexture = function () {
  30088. return this._texture;
  30089. };
  30090. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30091. return !this.isBlocking || this.isReady();
  30092. };
  30093. BaseTexture.prototype.isReady = function () {
  30094. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30095. this.delayLoad();
  30096. return false;
  30097. }
  30098. if (this._texture) {
  30099. return this._texture.isReady;
  30100. }
  30101. return false;
  30102. };
  30103. BaseTexture.prototype.getSize = function () {
  30104. if (this._texture) {
  30105. if (this._texture.width) {
  30106. this._cachedSize.width = this._texture.width;
  30107. this._cachedSize.height = this._texture.height;
  30108. return this._cachedSize;
  30109. }
  30110. if (this._texture._size) {
  30111. this._cachedSize.width = this._texture._size;
  30112. this._cachedSize.height = this._texture._size;
  30113. return this._cachedSize;
  30114. }
  30115. }
  30116. return this._cachedSize;
  30117. };
  30118. BaseTexture.prototype.getBaseSize = function () {
  30119. if (!this.isReady() || !this._texture)
  30120. return BABYLON.Size.Zero();
  30121. if (this._texture._size) {
  30122. return new BABYLON.Size(this._texture._size, this._texture._size);
  30123. }
  30124. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30125. };
  30126. BaseTexture.prototype.scale = function (ratio) {
  30127. };
  30128. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30129. get: function () {
  30130. return false;
  30131. },
  30132. enumerable: true,
  30133. configurable: true
  30134. });
  30135. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30136. if (!this._scene) {
  30137. return null;
  30138. }
  30139. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30140. for (var index = 0; index < texturesCache.length; index++) {
  30141. var texturesCacheEntry = texturesCache[index];
  30142. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30143. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30144. texturesCacheEntry.incrementReferences();
  30145. return texturesCacheEntry;
  30146. }
  30147. }
  30148. }
  30149. return null;
  30150. };
  30151. BaseTexture.prototype._rebuild = function () {
  30152. };
  30153. BaseTexture.prototype.delayLoad = function () {
  30154. };
  30155. BaseTexture.prototype.clone = function () {
  30156. return null;
  30157. };
  30158. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30159. get: function () {
  30160. if (!this._texture) {
  30161. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30162. }
  30163. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30164. },
  30165. enumerable: true,
  30166. configurable: true
  30167. });
  30168. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30169. get: function () {
  30170. if (!this._texture) {
  30171. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30172. }
  30173. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30174. },
  30175. enumerable: true,
  30176. configurable: true
  30177. });
  30178. /**
  30179. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30180. * This will returns an RGBA array buffer containing either in values (0-255) or
  30181. * float values (0-1) depending of the underlying buffer type.
  30182. * @param faceIndex The face of the texture to read (in case of cube texture)
  30183. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30184. * @returns The Array buffer containing the pixels data.
  30185. */
  30186. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30187. if (faceIndex === void 0) { faceIndex = 0; }
  30188. if (level === void 0) { level = 0; }
  30189. if (!this._texture) {
  30190. return null;
  30191. }
  30192. var size = this.getSize();
  30193. var width = size.width;
  30194. var height = size.height;
  30195. var scene = this.getScene();
  30196. if (!scene) {
  30197. return null;
  30198. }
  30199. var engine = scene.getEngine();
  30200. if (level != 0) {
  30201. width = width / Math.pow(2, level);
  30202. height = height / Math.pow(2, level);
  30203. width = Math.round(width);
  30204. height = Math.round(height);
  30205. }
  30206. if (this._texture.isCube) {
  30207. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30208. }
  30209. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30210. };
  30211. BaseTexture.prototype.releaseInternalTexture = function () {
  30212. if (this._texture) {
  30213. this._texture.dispose();
  30214. this._texture = null;
  30215. }
  30216. };
  30217. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30218. get: function () {
  30219. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30220. return null;
  30221. }
  30222. if (!this._texture._sphericalPolynomial) {
  30223. this._texture._sphericalPolynomial =
  30224. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30225. }
  30226. return this._texture._sphericalPolynomial;
  30227. },
  30228. set: function (value) {
  30229. if (this._texture) {
  30230. this._texture._sphericalPolynomial = value;
  30231. }
  30232. },
  30233. enumerable: true,
  30234. configurable: true
  30235. });
  30236. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30237. get: function () {
  30238. if (this._texture) {
  30239. return this._texture._lodTextureHigh;
  30240. }
  30241. return null;
  30242. },
  30243. enumerable: true,
  30244. configurable: true
  30245. });
  30246. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30247. get: function () {
  30248. if (this._texture) {
  30249. return this._texture._lodTextureMid;
  30250. }
  30251. return null;
  30252. },
  30253. enumerable: true,
  30254. configurable: true
  30255. });
  30256. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30257. get: function () {
  30258. if (this._texture) {
  30259. return this._texture._lodTextureLow;
  30260. }
  30261. return null;
  30262. },
  30263. enumerable: true,
  30264. configurable: true
  30265. });
  30266. BaseTexture.prototype.dispose = function () {
  30267. if (!this._scene) {
  30268. return;
  30269. }
  30270. // Animations
  30271. this._scene.stopAnimation(this);
  30272. // Remove from scene
  30273. this._scene._removePendingData(this);
  30274. var index = this._scene.textures.indexOf(this);
  30275. if (index >= 0) {
  30276. this._scene.textures.splice(index, 1);
  30277. }
  30278. if (this._texture === undefined) {
  30279. return;
  30280. }
  30281. // Release
  30282. this.releaseInternalTexture();
  30283. // Callback
  30284. this.onDisposeObservable.notifyObservers(this);
  30285. this.onDisposeObservable.clear();
  30286. };
  30287. BaseTexture.prototype.serialize = function () {
  30288. if (!this.name) {
  30289. return null;
  30290. }
  30291. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30292. // Animations
  30293. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30294. return serializationObject;
  30295. };
  30296. BaseTexture.WhenAllReady = function (textures, callback) {
  30297. var numRemaining = textures.length;
  30298. if (numRemaining === 0) {
  30299. callback();
  30300. return;
  30301. }
  30302. var _loop_1 = function () {
  30303. texture = textures[i];
  30304. if (texture.isReady()) {
  30305. if (--numRemaining === 0) {
  30306. callback();
  30307. }
  30308. }
  30309. else {
  30310. onLoadObservable = texture.onLoadObservable;
  30311. var onLoadCallback_1 = function () {
  30312. onLoadObservable.removeCallback(onLoadCallback_1);
  30313. if (--numRemaining === 0) {
  30314. callback();
  30315. }
  30316. };
  30317. onLoadObservable.add(onLoadCallback_1);
  30318. }
  30319. };
  30320. var texture, onLoadObservable;
  30321. for (var i = 0; i < textures.length; i++) {
  30322. _loop_1();
  30323. }
  30324. };
  30325. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30326. __decorate([
  30327. BABYLON.serialize()
  30328. ], BaseTexture.prototype, "name", void 0);
  30329. __decorate([
  30330. BABYLON.serialize("hasAlpha")
  30331. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30332. __decorate([
  30333. BABYLON.serialize()
  30334. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30335. __decorate([
  30336. BABYLON.serialize()
  30337. ], BaseTexture.prototype, "level", void 0);
  30338. __decorate([
  30339. BABYLON.serialize()
  30340. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30341. __decorate([
  30342. BABYLON.serialize("coordinatesMode")
  30343. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30344. __decorate([
  30345. BABYLON.serialize()
  30346. ], BaseTexture.prototype, "wrapU", void 0);
  30347. __decorate([
  30348. BABYLON.serialize()
  30349. ], BaseTexture.prototype, "wrapV", void 0);
  30350. __decorate([
  30351. BABYLON.serialize()
  30352. ], BaseTexture.prototype, "wrapR", void 0);
  30353. __decorate([
  30354. BABYLON.serialize()
  30355. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30356. __decorate([
  30357. BABYLON.serialize()
  30358. ], BaseTexture.prototype, "isCube", void 0);
  30359. __decorate([
  30360. BABYLON.serialize()
  30361. ], BaseTexture.prototype, "is3D", void 0);
  30362. __decorate([
  30363. BABYLON.serialize()
  30364. ], BaseTexture.prototype, "gammaSpace", void 0);
  30365. __decorate([
  30366. BABYLON.serialize()
  30367. ], BaseTexture.prototype, "invertZ", void 0);
  30368. __decorate([
  30369. BABYLON.serialize()
  30370. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30371. __decorate([
  30372. BABYLON.serialize()
  30373. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30374. __decorate([
  30375. BABYLON.serialize()
  30376. ], BaseTexture.prototype, "lodGenerationScale", null);
  30377. __decorate([
  30378. BABYLON.serialize()
  30379. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30380. return BaseTexture;
  30381. }());
  30382. BABYLON.BaseTexture = BaseTexture;
  30383. })(BABYLON || (BABYLON = {}));
  30384. //# sourceMappingURL=babylon.baseTexture.js.map
  30385. var BABYLON;
  30386. (function (BABYLON) {
  30387. var Texture = /** @class */ (function (_super) {
  30388. __extends(Texture, _super);
  30389. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30390. if (noMipmap === void 0) { noMipmap = false; }
  30391. if (invertY === void 0) { invertY = true; }
  30392. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30393. if (onLoad === void 0) { onLoad = null; }
  30394. if (onError === void 0) { onError = null; }
  30395. if (buffer === void 0) { buffer = null; }
  30396. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30397. var _this = _super.call(this, scene) || this;
  30398. _this.uOffset = 0;
  30399. _this.vOffset = 0;
  30400. _this.uScale = 1.0;
  30401. _this.vScale = 1.0;
  30402. _this.uAng = 0;
  30403. _this.vAng = 0;
  30404. _this.wAng = 0;
  30405. /**
  30406. * Defines the center of rotation (U)
  30407. */
  30408. _this.uRotationCenter = 0.5;
  30409. /**
  30410. * Defines the center of rotation (V)
  30411. */
  30412. _this.vRotationCenter = 0.5;
  30413. /**
  30414. * Defines the center of rotation (W)
  30415. */
  30416. _this.wRotationCenter = 0.5;
  30417. _this._isBlocking = true;
  30418. _this.name = url || "";
  30419. _this.url = url;
  30420. _this._noMipmap = noMipmap;
  30421. _this._invertY = invertY;
  30422. _this._samplingMode = samplingMode;
  30423. _this._buffer = buffer;
  30424. _this._deleteBuffer = deleteBuffer;
  30425. if (format) {
  30426. _this._format = format;
  30427. }
  30428. scene = _this.getScene();
  30429. if (!scene) {
  30430. return _this;
  30431. }
  30432. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30433. var load = function () {
  30434. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30435. _this.onLoadObservable.notifyObservers(_this);
  30436. }
  30437. if (onLoad) {
  30438. onLoad();
  30439. }
  30440. if (!_this.isBlocking && scene) {
  30441. scene.resetCachedMaterial();
  30442. }
  30443. };
  30444. if (!_this.url) {
  30445. _this._delayedOnLoad = load;
  30446. _this._delayedOnError = onError;
  30447. return _this;
  30448. }
  30449. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30450. if (!_this._texture) {
  30451. if (!scene.useDelayedTextureLoading) {
  30452. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30453. if (deleteBuffer) {
  30454. delete _this._buffer;
  30455. }
  30456. }
  30457. else {
  30458. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30459. _this._delayedOnLoad = load;
  30460. _this._delayedOnError = onError;
  30461. }
  30462. }
  30463. else {
  30464. if (_this._texture.isReady) {
  30465. BABYLON.Tools.SetImmediate(function () { return load(); });
  30466. }
  30467. else {
  30468. _this._texture.onLoadedObservable.add(load);
  30469. }
  30470. }
  30471. return _this;
  30472. }
  30473. Object.defineProperty(Texture.prototype, "noMipmap", {
  30474. get: function () {
  30475. return this._noMipmap;
  30476. },
  30477. enumerable: true,
  30478. configurable: true
  30479. });
  30480. Object.defineProperty(Texture.prototype, "isBlocking", {
  30481. get: function () {
  30482. return this._isBlocking;
  30483. },
  30484. set: function (value) {
  30485. this._isBlocking = value;
  30486. },
  30487. enumerable: true,
  30488. configurable: true
  30489. });
  30490. Object.defineProperty(Texture.prototype, "samplingMode", {
  30491. get: function () {
  30492. return this._samplingMode;
  30493. },
  30494. enumerable: true,
  30495. configurable: true
  30496. });
  30497. /**
  30498. * Update the url (and optional buffer) of this texture if url was null during construction.
  30499. * @param url the url of the texture
  30500. * @param buffer the buffer of the texture (defaults to null)
  30501. */
  30502. Texture.prototype.updateURL = function (url, buffer) {
  30503. if (buffer === void 0) { buffer = null; }
  30504. if (this.url) {
  30505. throw new Error("URL is already set");
  30506. }
  30507. this.url = url;
  30508. this._buffer = buffer;
  30509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30510. this.delayLoad();
  30511. };
  30512. Texture.prototype.delayLoad = function () {
  30513. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30514. return;
  30515. }
  30516. var scene = this.getScene();
  30517. if (!scene) {
  30518. return;
  30519. }
  30520. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30521. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30522. if (!this._texture) {
  30523. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30524. if (this._deleteBuffer) {
  30525. delete this._buffer;
  30526. }
  30527. }
  30528. else {
  30529. if (this._delayedOnLoad) {
  30530. if (this._texture.isReady) {
  30531. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30532. }
  30533. else {
  30534. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30535. }
  30536. }
  30537. }
  30538. this._delayedOnLoad = null;
  30539. this._delayedOnError = null;
  30540. };
  30541. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30542. if (!this._texture) {
  30543. return;
  30544. }
  30545. var scene = this.getScene();
  30546. if (!scene) {
  30547. return;
  30548. }
  30549. this._samplingMode = samplingMode;
  30550. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30551. };
  30552. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30553. x *= this.uScale;
  30554. y *= this.vScale;
  30555. x -= this.uRotationCenter * this.uScale;
  30556. y -= this.vRotationCenter * this.vScale;
  30557. z -= this.wRotationCenter;
  30558. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30559. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30560. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30561. t.z += this.wRotationCenter;
  30562. };
  30563. Texture.prototype.getTextureMatrix = function () {
  30564. var _this = this;
  30565. if (this.uOffset === this._cachedUOffset &&
  30566. this.vOffset === this._cachedVOffset &&
  30567. this.uScale === this._cachedUScale &&
  30568. this.vScale === this._cachedVScale &&
  30569. this.uAng === this._cachedUAng &&
  30570. this.vAng === this._cachedVAng &&
  30571. this.wAng === this._cachedWAng) {
  30572. return this._cachedTextureMatrix;
  30573. }
  30574. this._cachedUOffset = this.uOffset;
  30575. this._cachedVOffset = this.vOffset;
  30576. this._cachedUScale = this.uScale;
  30577. this._cachedVScale = this.vScale;
  30578. this._cachedUAng = this.uAng;
  30579. this._cachedVAng = this.vAng;
  30580. this._cachedWAng = this.wAng;
  30581. if (!this._cachedTextureMatrix) {
  30582. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30583. this._rowGenerationMatrix = new BABYLON.Matrix();
  30584. this._t0 = BABYLON.Vector3.Zero();
  30585. this._t1 = BABYLON.Vector3.Zero();
  30586. this._t2 = BABYLON.Vector3.Zero();
  30587. }
  30588. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30589. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30590. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30591. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30592. this._t1.subtractInPlace(this._t0);
  30593. this._t2.subtractInPlace(this._t0);
  30594. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30595. this._cachedTextureMatrix.m[0] = this._t1.x;
  30596. this._cachedTextureMatrix.m[1] = this._t1.y;
  30597. this._cachedTextureMatrix.m[2] = this._t1.z;
  30598. this._cachedTextureMatrix.m[4] = this._t2.x;
  30599. this._cachedTextureMatrix.m[5] = this._t2.y;
  30600. this._cachedTextureMatrix.m[6] = this._t2.z;
  30601. this._cachedTextureMatrix.m[8] = this._t0.x;
  30602. this._cachedTextureMatrix.m[9] = this._t0.y;
  30603. this._cachedTextureMatrix.m[10] = this._t0.z;
  30604. var scene = this.getScene();
  30605. if (!scene) {
  30606. return this._cachedTextureMatrix;
  30607. }
  30608. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30609. return mat.hasTexture(_this);
  30610. });
  30611. return this._cachedTextureMatrix;
  30612. };
  30613. Texture.prototype.getReflectionTextureMatrix = function () {
  30614. var _this = this;
  30615. var scene = this.getScene();
  30616. if (!scene) {
  30617. return this._cachedTextureMatrix;
  30618. }
  30619. if (this.uOffset === this._cachedUOffset &&
  30620. this.vOffset === this._cachedVOffset &&
  30621. this.uScale === this._cachedUScale &&
  30622. this.vScale === this._cachedVScale &&
  30623. this.coordinatesMode === this._cachedCoordinatesMode) {
  30624. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30625. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30626. return this._cachedTextureMatrix;
  30627. }
  30628. }
  30629. else {
  30630. return this._cachedTextureMatrix;
  30631. }
  30632. }
  30633. if (!this._cachedTextureMatrix) {
  30634. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30635. }
  30636. if (!this._projectionModeMatrix) {
  30637. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30638. }
  30639. this._cachedUOffset = this.uOffset;
  30640. this._cachedVOffset = this.vOffset;
  30641. this._cachedUScale = this.uScale;
  30642. this._cachedVScale = this.vScale;
  30643. this._cachedCoordinatesMode = this.coordinatesMode;
  30644. switch (this.coordinatesMode) {
  30645. case Texture.PLANAR_MODE:
  30646. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30647. this._cachedTextureMatrix[0] = this.uScale;
  30648. this._cachedTextureMatrix[5] = this.vScale;
  30649. this._cachedTextureMatrix[12] = this.uOffset;
  30650. this._cachedTextureMatrix[13] = this.vOffset;
  30651. break;
  30652. case Texture.PROJECTION_MODE:
  30653. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30654. this._projectionModeMatrix.m[0] = 0.5;
  30655. this._projectionModeMatrix.m[5] = -0.5;
  30656. this._projectionModeMatrix.m[10] = 0.0;
  30657. this._projectionModeMatrix.m[12] = 0.5;
  30658. this._projectionModeMatrix.m[13] = 0.5;
  30659. this._projectionModeMatrix.m[14] = 1.0;
  30660. this._projectionModeMatrix.m[15] = 1.0;
  30661. var projectionMatrix = scene.getProjectionMatrix();
  30662. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30663. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30664. break;
  30665. default:
  30666. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30667. break;
  30668. }
  30669. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30670. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30671. });
  30672. return this._cachedTextureMatrix;
  30673. };
  30674. Texture.prototype.clone = function () {
  30675. var _this = this;
  30676. return BABYLON.SerializationHelper.Clone(function () {
  30677. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30678. }, this);
  30679. };
  30680. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30681. get: function () {
  30682. if (!this._onLoadObservable) {
  30683. this._onLoadObservable = new BABYLON.Observable();
  30684. }
  30685. return this._onLoadObservable;
  30686. },
  30687. enumerable: true,
  30688. configurable: true
  30689. });
  30690. Texture.prototype.serialize = function () {
  30691. var serializationObject = _super.prototype.serialize.call(this);
  30692. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30693. serializationObject.base64String = this._buffer;
  30694. serializationObject.name = serializationObject.name.replace("data:", "");
  30695. }
  30696. serializationObject.invertY = this._invertY;
  30697. serializationObject.samplingMode = this.samplingMode;
  30698. return serializationObject;
  30699. };
  30700. Texture.prototype.getClassName = function () {
  30701. return "Texture";
  30702. };
  30703. Texture.prototype.dispose = function () {
  30704. _super.prototype.dispose.call(this);
  30705. if (this._onLoadObservable) {
  30706. this._onLoadObservable.clear();
  30707. this._onLoadObservable = null;
  30708. }
  30709. this._delayedOnLoad = null;
  30710. this._delayedOnError = null;
  30711. };
  30712. // Statics
  30713. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30714. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30715. if (onLoad === void 0) { onLoad = null; }
  30716. if (onError === void 0) { onError = null; }
  30717. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30718. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30719. };
  30720. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30721. if (parsedTexture.customType) {
  30722. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30723. // Update Sampling Mode
  30724. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30725. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30726. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30727. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30728. }
  30729. }
  30730. return parsedCustomTexture;
  30731. }
  30732. if (parsedTexture.isCube) {
  30733. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30734. }
  30735. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30736. return null;
  30737. }
  30738. var texture = BABYLON.SerializationHelper.Parse(function () {
  30739. var generateMipMaps = true;
  30740. if (parsedTexture.noMipmap) {
  30741. generateMipMaps = false;
  30742. }
  30743. if (parsedTexture.mirrorPlane) {
  30744. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30745. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30746. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30747. return mirrorTexture;
  30748. }
  30749. else if (parsedTexture.isRenderTarget) {
  30750. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30751. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30752. return renderTargetTexture;
  30753. }
  30754. else {
  30755. var texture;
  30756. if (parsedTexture.base64String) {
  30757. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30758. }
  30759. else {
  30760. var url = rootUrl + parsedTexture.name;
  30761. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30762. url = parsedTexture.url;
  30763. }
  30764. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30765. }
  30766. return texture;
  30767. }
  30768. }, parsedTexture, scene);
  30769. // Update Sampling Mode
  30770. if (parsedTexture.samplingMode) {
  30771. var sampling = parsedTexture.samplingMode;
  30772. if (texture._samplingMode !== sampling) {
  30773. texture.updateSamplingMode(sampling);
  30774. }
  30775. }
  30776. // Animations
  30777. if (parsedTexture.animations) {
  30778. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30779. var parsedAnimation = parsedTexture.animations[animationIndex];
  30780. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30781. }
  30782. }
  30783. return texture;
  30784. };
  30785. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30786. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30787. if (noMipmap === void 0) { noMipmap = false; }
  30788. if (invertY === void 0) { invertY = true; }
  30789. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30790. if (onLoad === void 0) { onLoad = null; }
  30791. if (onError === void 0) { onError = null; }
  30792. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30793. if (name.substr(0, 5) !== "data:") {
  30794. name = "data:" + name;
  30795. }
  30796. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30797. };
  30798. // Constants
  30799. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30800. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30801. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30802. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30803. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30804. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30805. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30806. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30807. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30808. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30809. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30810. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30811. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30812. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30813. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30814. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30815. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30816. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30817. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30818. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30819. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30820. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30821. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30822. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30823. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30824. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30825. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30826. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30827. /**
  30828. * 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
  30829. */
  30830. Texture.UseSerializedUrlIfAny = false;
  30831. __decorate([
  30832. BABYLON.serialize()
  30833. ], Texture.prototype, "url", void 0);
  30834. __decorate([
  30835. BABYLON.serialize()
  30836. ], Texture.prototype, "uOffset", void 0);
  30837. __decorate([
  30838. BABYLON.serialize()
  30839. ], Texture.prototype, "vOffset", void 0);
  30840. __decorate([
  30841. BABYLON.serialize()
  30842. ], Texture.prototype, "uScale", void 0);
  30843. __decorate([
  30844. BABYLON.serialize()
  30845. ], Texture.prototype, "vScale", void 0);
  30846. __decorate([
  30847. BABYLON.serialize()
  30848. ], Texture.prototype, "uAng", void 0);
  30849. __decorate([
  30850. BABYLON.serialize()
  30851. ], Texture.prototype, "vAng", void 0);
  30852. __decorate([
  30853. BABYLON.serialize()
  30854. ], Texture.prototype, "wAng", void 0);
  30855. __decorate([
  30856. BABYLON.serialize()
  30857. ], Texture.prototype, "uRotationCenter", void 0);
  30858. __decorate([
  30859. BABYLON.serialize()
  30860. ], Texture.prototype, "vRotationCenter", void 0);
  30861. __decorate([
  30862. BABYLON.serialize()
  30863. ], Texture.prototype, "wRotationCenter", void 0);
  30864. __decorate([
  30865. BABYLON.serialize()
  30866. ], Texture.prototype, "isBlocking", null);
  30867. return Texture;
  30868. }(BABYLON.BaseTexture));
  30869. BABYLON.Texture = Texture;
  30870. })(BABYLON || (BABYLON = {}));
  30871. //# sourceMappingURL=babylon.texture.js.map
  30872. var BABYLON;
  30873. (function (BABYLON) {
  30874. /**
  30875. * @hidden
  30876. **/
  30877. var _InstancesBatch = /** @class */ (function () {
  30878. function _InstancesBatch() {
  30879. this.mustReturn = false;
  30880. this.visibleInstances = new Array();
  30881. this.renderSelf = new Array();
  30882. }
  30883. return _InstancesBatch;
  30884. }());
  30885. BABYLON._InstancesBatch = _InstancesBatch;
  30886. var Mesh = /** @class */ (function (_super) {
  30887. __extends(Mesh, _super);
  30888. /**
  30889. * @constructor
  30890. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30891. * @param {Scene} scene The scene to add this mesh to.
  30892. * @param {Node} parent The parent of this mesh, if it has one
  30893. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30894. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30895. * When false, achieved by calling a clone(), also passing False.
  30896. * This will make creation of children, recursive.
  30897. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30898. */
  30899. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30900. if (scene === void 0) { scene = null; }
  30901. if (parent === void 0) { parent = null; }
  30902. if (source === void 0) { source = null; }
  30903. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30904. var _this = _super.call(this, name, scene) || this;
  30905. // Events
  30906. /**
  30907. * An event triggered before rendering the mesh
  30908. */
  30909. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30910. /**
  30911. * An event triggered after rendering the mesh
  30912. */
  30913. _this.onAfterRenderObservable = new BABYLON.Observable();
  30914. /**
  30915. * An event triggered before drawing the mesh
  30916. */
  30917. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30918. // Members
  30919. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30920. _this.instances = new Array();
  30921. _this._LODLevels = new Array();
  30922. _this._visibleInstances = {};
  30923. _this._renderIdForInstances = new Array();
  30924. _this._batchCache = new _InstancesBatch();
  30925. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30926. // Use by builder only to know what orientation were the mesh build in.
  30927. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30928. _this.overrideMaterialSideOrientation = null;
  30929. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30930. // Will be used to save a source mesh reference, If any
  30931. _this._source = null;
  30932. scene = _this.getScene();
  30933. if (source) {
  30934. // Geometry
  30935. if (source._geometry) {
  30936. source._geometry.applyToMesh(_this);
  30937. }
  30938. // Deep copy
  30939. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30940. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  30941. // Source mesh
  30942. _this._source = source;
  30943. // Metadata
  30944. if (source.metadata && source.metadata.clone) {
  30945. _this.metadata = source.metadata.clone();
  30946. }
  30947. else {
  30948. _this.metadata = source.metadata;
  30949. }
  30950. // Tags
  30951. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30952. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30953. }
  30954. // Parent
  30955. _this.parent = source.parent;
  30956. // Pivot
  30957. _this.setPivotMatrix(source.getPivotMatrix());
  30958. _this.id = name + "." + source.id;
  30959. // Material
  30960. _this.material = source.material;
  30961. var index;
  30962. if (!doNotCloneChildren) {
  30963. // Children
  30964. var directDescendants = source.getDescendants(true);
  30965. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30966. var child = directDescendants[index_1];
  30967. if (child.clone) {
  30968. child.clone(name + "." + child.name, _this);
  30969. }
  30970. }
  30971. }
  30972. // Physics clone
  30973. var physicsEngine = _this.getScene().getPhysicsEngine();
  30974. if (clonePhysicsImpostor && physicsEngine) {
  30975. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30976. if (impostor) {
  30977. _this.physicsImpostor = impostor.clone(_this);
  30978. }
  30979. }
  30980. // Particles
  30981. for (index = 0; index < scene.particleSystems.length; index++) {
  30982. var system = scene.particleSystems[index];
  30983. if (system.emitter === source) {
  30984. system.clone(system.name, _this);
  30985. }
  30986. }
  30987. _this.refreshBoundingInfo();
  30988. _this.computeWorldMatrix(true);
  30989. }
  30990. // Parent
  30991. if (parent !== null) {
  30992. _this.parent = parent;
  30993. }
  30994. return _this;
  30995. }
  30996. Object.defineProperty(Mesh, "FRONTSIDE", {
  30997. /**
  30998. * Mesh side orientation : usually the external or front surface
  30999. */
  31000. get: function () {
  31001. return Mesh._FRONTSIDE;
  31002. },
  31003. enumerable: true,
  31004. configurable: true
  31005. });
  31006. Object.defineProperty(Mesh, "BACKSIDE", {
  31007. /**
  31008. * Mesh side orientation : usually the internal or back surface
  31009. */
  31010. get: function () {
  31011. return Mesh._BACKSIDE;
  31012. },
  31013. enumerable: true,
  31014. configurable: true
  31015. });
  31016. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31017. /**
  31018. * Mesh side orientation : both internal and external or front and back surfaces
  31019. */
  31020. get: function () {
  31021. return Mesh._DOUBLESIDE;
  31022. },
  31023. enumerable: true,
  31024. configurable: true
  31025. });
  31026. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31027. /**
  31028. * Mesh side orientation : by default, `FRONTSIDE`
  31029. */
  31030. get: function () {
  31031. return Mesh._DEFAULTSIDE;
  31032. },
  31033. enumerable: true,
  31034. configurable: true
  31035. });
  31036. Object.defineProperty(Mesh, "NO_CAP", {
  31037. /**
  31038. * Mesh cap setting : no cap
  31039. */
  31040. get: function () {
  31041. return Mesh._NO_CAP;
  31042. },
  31043. enumerable: true,
  31044. configurable: true
  31045. });
  31046. Object.defineProperty(Mesh, "CAP_START", {
  31047. /**
  31048. * Mesh cap setting : one cap at the beginning of the mesh
  31049. */
  31050. get: function () {
  31051. return Mesh._CAP_START;
  31052. },
  31053. enumerable: true,
  31054. configurable: true
  31055. });
  31056. Object.defineProperty(Mesh, "CAP_END", {
  31057. /**
  31058. * Mesh cap setting : one cap at the end of the mesh
  31059. */
  31060. get: function () {
  31061. return Mesh._CAP_END;
  31062. },
  31063. enumerable: true,
  31064. configurable: true
  31065. });
  31066. Object.defineProperty(Mesh, "CAP_ALL", {
  31067. /**
  31068. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31069. */
  31070. get: function () {
  31071. return Mesh._CAP_ALL;
  31072. },
  31073. enumerable: true,
  31074. configurable: true
  31075. });
  31076. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31077. set: function (callback) {
  31078. if (this._onBeforeDrawObserver) {
  31079. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31080. }
  31081. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31082. },
  31083. enumerable: true,
  31084. configurable: true
  31085. });
  31086. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31087. get: function () {
  31088. return this._morphTargetManager;
  31089. },
  31090. set: function (value) {
  31091. if (this._morphTargetManager === value) {
  31092. return;
  31093. }
  31094. this._morphTargetManager = value;
  31095. this._syncGeometryWithMorphTargetManager();
  31096. },
  31097. enumerable: true,
  31098. configurable: true
  31099. });
  31100. Object.defineProperty(Mesh.prototype, "source", {
  31101. get: function () {
  31102. return this._source;
  31103. },
  31104. enumerable: true,
  31105. configurable: true
  31106. });
  31107. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31108. get: function () {
  31109. return this._unIndexed;
  31110. },
  31111. set: function (value) {
  31112. if (this._unIndexed !== value) {
  31113. this._unIndexed = value;
  31114. this._markSubMeshesAsAttributesDirty();
  31115. }
  31116. },
  31117. enumerable: true,
  31118. configurable: true
  31119. });
  31120. // Methods
  31121. /**
  31122. * Returns the string "Mesh".
  31123. */
  31124. Mesh.prototype.getClassName = function () {
  31125. return "Mesh";
  31126. };
  31127. /**
  31128. * Returns a string.
  31129. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31130. */
  31131. Mesh.prototype.toString = function (fullDetails) {
  31132. var ret = _super.prototype.toString.call(this, fullDetails);
  31133. ret += ", n vertices: " + this.getTotalVertices();
  31134. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31135. if (this.animations) {
  31136. for (var i = 0; i < this.animations.length; i++) {
  31137. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31138. }
  31139. }
  31140. if (fullDetails) {
  31141. if (this._geometry) {
  31142. var ib = this.getIndices();
  31143. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31144. if (vb && ib) {
  31145. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31146. }
  31147. }
  31148. else {
  31149. ret += ", flat shading: UNKNOWN";
  31150. }
  31151. }
  31152. return ret;
  31153. };
  31154. Mesh.prototype._unBindEffect = function () {
  31155. _super.prototype._unBindEffect.call(this);
  31156. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31157. var instance = _a[_i];
  31158. instance._unBindEffect();
  31159. }
  31160. };
  31161. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31162. /**
  31163. * True if the mesh has some Levels Of Details (LOD).
  31164. * Returns a boolean.
  31165. */
  31166. get: function () {
  31167. return this._LODLevels.length > 0;
  31168. },
  31169. enumerable: true,
  31170. configurable: true
  31171. });
  31172. /**
  31173. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31174. * @returns an array of {BABYLON.MeshLODLevel}
  31175. */
  31176. Mesh.prototype.getLODLevels = function () {
  31177. return this._LODLevels;
  31178. };
  31179. Mesh.prototype._sortLODLevels = function () {
  31180. this._LODLevels.sort(function (a, b) {
  31181. if (a.distance < b.distance) {
  31182. return 1;
  31183. }
  31184. if (a.distance > b.distance) {
  31185. return -1;
  31186. }
  31187. return 0;
  31188. });
  31189. };
  31190. /**
  31191. * Add a mesh as LOD level triggered at the given distance.
  31192. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31193. * @param distance The distance from the center of the object to show this level
  31194. * @param mesh The mesh to be added as LOD level (can be null)
  31195. * @return This mesh (for chaining)
  31196. */
  31197. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31198. if (mesh && mesh._masterMesh) {
  31199. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31200. return this;
  31201. }
  31202. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31203. this._LODLevels.push(level);
  31204. if (mesh) {
  31205. mesh._masterMesh = this;
  31206. }
  31207. this._sortLODLevels();
  31208. return this;
  31209. };
  31210. /**
  31211. * Returns the LOD level mesh at the passed distance or null if not found.
  31212. * It is related to the method `addLODLevel(distance, mesh)`.
  31213. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31214. * Returns an object Mesh or `null`.
  31215. */
  31216. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31217. for (var index = 0; index < this._LODLevels.length; index++) {
  31218. var level = this._LODLevels[index];
  31219. if (level.distance === distance) {
  31220. return level.mesh;
  31221. }
  31222. }
  31223. return null;
  31224. };
  31225. /**
  31226. * Remove a mesh from the LOD array
  31227. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31228. * @param {Mesh} mesh The mesh to be removed.
  31229. * @return {Mesh} This mesh (for chaining)
  31230. */
  31231. Mesh.prototype.removeLODLevel = function (mesh) {
  31232. for (var index = 0; index < this._LODLevels.length; index++) {
  31233. if (this._LODLevels[index].mesh === mesh) {
  31234. this._LODLevels.splice(index, 1);
  31235. if (mesh) {
  31236. mesh._masterMesh = null;
  31237. }
  31238. }
  31239. }
  31240. this._sortLODLevels();
  31241. return this;
  31242. };
  31243. /**
  31244. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31245. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31246. */
  31247. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31248. if (!this._LODLevels || this._LODLevels.length === 0) {
  31249. return this;
  31250. }
  31251. var bSphere;
  31252. if (boundingSphere) {
  31253. bSphere = boundingSphere;
  31254. }
  31255. else {
  31256. var boundingInfo = this.getBoundingInfo();
  31257. bSphere = boundingInfo.boundingSphere;
  31258. }
  31259. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31260. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31261. if (this.onLODLevelSelection) {
  31262. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31263. }
  31264. return this;
  31265. }
  31266. for (var index = 0; index < this._LODLevels.length; index++) {
  31267. var level = this._LODLevels[index];
  31268. if (level.distance < distanceToCamera) {
  31269. if (level.mesh) {
  31270. level.mesh._preActivate();
  31271. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31272. }
  31273. if (this.onLODLevelSelection) {
  31274. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31275. }
  31276. return level.mesh;
  31277. }
  31278. }
  31279. if (this.onLODLevelSelection) {
  31280. this.onLODLevelSelection(distanceToCamera, this, this);
  31281. }
  31282. return this;
  31283. };
  31284. Object.defineProperty(Mesh.prototype, "geometry", {
  31285. /**
  31286. * Returns the mesh internal Geometry object.
  31287. */
  31288. get: function () {
  31289. return this._geometry;
  31290. },
  31291. enumerable: true,
  31292. configurable: true
  31293. });
  31294. /**
  31295. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31296. */
  31297. Mesh.prototype.getTotalVertices = function () {
  31298. if (this._geometry === null || this._geometry === undefined) {
  31299. return 0;
  31300. }
  31301. return this._geometry.getTotalVertices();
  31302. };
  31303. /**
  31304. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31305. * 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.
  31306. * You can force the copy with forceCopy === true
  31307. * Returns null if the mesh has no geometry or no vertex buffer.
  31308. * Possible `kind` values :
  31309. * - BABYLON.VertexBuffer.PositionKind
  31310. * - BABYLON.VertexBuffer.UVKind
  31311. * - BABYLON.VertexBuffer.UV2Kind
  31312. * - BABYLON.VertexBuffer.UV3Kind
  31313. * - BABYLON.VertexBuffer.UV4Kind
  31314. * - BABYLON.VertexBuffer.UV5Kind
  31315. * - BABYLON.VertexBuffer.UV6Kind
  31316. * - BABYLON.VertexBuffer.ColorKind
  31317. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31318. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31319. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31320. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31321. */
  31322. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31323. if (!this._geometry) {
  31324. return null;
  31325. }
  31326. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31327. };
  31328. /**
  31329. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31330. * Returns `null` if the mesh has no geometry.
  31331. * Possible `kind` values :
  31332. * - BABYLON.VertexBuffer.PositionKind
  31333. * - BABYLON.VertexBuffer.UVKind
  31334. * - BABYLON.VertexBuffer.UV2Kind
  31335. * - BABYLON.VertexBuffer.UV3Kind
  31336. * - BABYLON.VertexBuffer.UV4Kind
  31337. * - BABYLON.VertexBuffer.UV5Kind
  31338. * - BABYLON.VertexBuffer.UV6Kind
  31339. * - BABYLON.VertexBuffer.ColorKind
  31340. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31341. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31342. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31343. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31344. */
  31345. Mesh.prototype.getVertexBuffer = function (kind) {
  31346. if (!this._geometry) {
  31347. return null;
  31348. }
  31349. return this._geometry.getVertexBuffer(kind);
  31350. };
  31351. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31352. if (!this._geometry) {
  31353. if (this._delayInfo) {
  31354. return this._delayInfo.indexOf(kind) !== -1;
  31355. }
  31356. return false;
  31357. }
  31358. return this._geometry.isVerticesDataPresent(kind);
  31359. };
  31360. /**
  31361. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31362. * Possible `kind` values :
  31363. * - BABYLON.VertexBuffer.PositionKind
  31364. * - BABYLON.VertexBuffer.UVKind
  31365. * - BABYLON.VertexBuffer.UV2Kind
  31366. * - BABYLON.VertexBuffer.UV3Kind
  31367. * - BABYLON.VertexBuffer.UV4Kind
  31368. * - BABYLON.VertexBuffer.UV5Kind
  31369. * - BABYLON.VertexBuffer.UV6Kind
  31370. * - BABYLON.VertexBuffer.ColorKind
  31371. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31372. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31373. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31374. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31375. */
  31376. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31377. if (!this._geometry) {
  31378. if (this._delayInfo) {
  31379. return this._delayInfo.indexOf(kind) !== -1;
  31380. }
  31381. return false;
  31382. }
  31383. return this._geometry.isVertexBufferUpdatable(kind);
  31384. };
  31385. /**
  31386. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31387. * Possible `kind` values :
  31388. * - BABYLON.VertexBuffer.PositionKind
  31389. * - BABYLON.VertexBuffer.UVKind
  31390. * - BABYLON.VertexBuffer.UV2Kind
  31391. * - BABYLON.VertexBuffer.UV3Kind
  31392. * - BABYLON.VertexBuffer.UV4Kind
  31393. * - BABYLON.VertexBuffer.UV5Kind
  31394. * - BABYLON.VertexBuffer.UV6Kind
  31395. * - BABYLON.VertexBuffer.ColorKind
  31396. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31397. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31398. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31399. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31400. */
  31401. Mesh.prototype.getVerticesDataKinds = function () {
  31402. if (!this._geometry) {
  31403. var result = new Array();
  31404. if (this._delayInfo) {
  31405. this._delayInfo.forEach(function (kind, index, array) {
  31406. result.push(kind);
  31407. });
  31408. }
  31409. return result;
  31410. }
  31411. return this._geometry.getVerticesDataKinds();
  31412. };
  31413. /**
  31414. * Returns a positive integer : the total number of indices in this mesh geometry.
  31415. * Returns zero if the mesh has no geometry.
  31416. */
  31417. Mesh.prototype.getTotalIndices = function () {
  31418. if (!this._geometry) {
  31419. return 0;
  31420. }
  31421. return this._geometry.getTotalIndices();
  31422. };
  31423. /**
  31424. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31425. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31426. * Returns an empty array if the mesh has no geometry.
  31427. */
  31428. Mesh.prototype.getIndices = function (copyWhenShared) {
  31429. if (!this._geometry) {
  31430. return [];
  31431. }
  31432. return this._geometry.getIndices(copyWhenShared);
  31433. };
  31434. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31435. get: function () {
  31436. return this._masterMesh !== null && this._masterMesh !== undefined;
  31437. },
  31438. enumerable: true,
  31439. configurable: true
  31440. });
  31441. /**
  31442. * Determine if the current mesh is ready to be rendered
  31443. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31444. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31445. * @returns true if all associated assets are ready (material, textures, shaders)
  31446. */
  31447. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31448. if (completeCheck === void 0) { completeCheck = false; }
  31449. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31450. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31451. return false;
  31452. }
  31453. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31454. return false;
  31455. }
  31456. if (!this.subMeshes || this.subMeshes.length === 0) {
  31457. return true;
  31458. }
  31459. if (!completeCheck) {
  31460. return true;
  31461. }
  31462. var engine = this.getEngine();
  31463. var scene = this.getScene();
  31464. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31465. this.computeWorldMatrix();
  31466. var mat = this.material || scene.defaultMaterial;
  31467. if (mat) {
  31468. if (mat.storeEffectOnSubMeshes) {
  31469. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31470. var subMesh = _a[_i];
  31471. var effectiveMaterial = subMesh.getMaterial();
  31472. if (effectiveMaterial) {
  31473. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31474. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31475. return false;
  31476. }
  31477. }
  31478. else {
  31479. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31480. return false;
  31481. }
  31482. }
  31483. }
  31484. }
  31485. }
  31486. else {
  31487. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31488. return false;
  31489. }
  31490. }
  31491. }
  31492. // Shadows
  31493. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31494. var light = _c[_b];
  31495. var generator = light.getShadowGenerator();
  31496. if (generator) {
  31497. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31498. var subMesh = _e[_d];
  31499. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31500. return false;
  31501. }
  31502. }
  31503. }
  31504. }
  31505. // LOD
  31506. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31507. var lod = _g[_f];
  31508. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31509. return false;
  31510. }
  31511. }
  31512. return true;
  31513. };
  31514. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31515. /**
  31516. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31517. * This property is pertinent only for updatable parametric shapes.
  31518. */
  31519. get: function () {
  31520. return this._areNormalsFrozen;
  31521. },
  31522. enumerable: true,
  31523. configurable: true
  31524. });
  31525. /**
  31526. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31527. * It has no effect at all on other shapes.
  31528. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31529. * Returns the Mesh.
  31530. */
  31531. Mesh.prototype.freezeNormals = function () {
  31532. this._areNormalsFrozen = true;
  31533. return this;
  31534. };
  31535. /**
  31536. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31537. * It has no effect at all on other shapes.
  31538. * It reactivates the mesh normals computation if it was previously frozen.
  31539. * Returns the Mesh.
  31540. */
  31541. Mesh.prototype.unfreezeNormals = function () {
  31542. this._areNormalsFrozen = false;
  31543. return this;
  31544. };
  31545. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31546. /**
  31547. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31548. */
  31549. set: function (count) {
  31550. this._overridenInstanceCount = count;
  31551. },
  31552. enumerable: true,
  31553. configurable: true
  31554. });
  31555. // Methods
  31556. Mesh.prototype._preActivate = function () {
  31557. var sceneRenderId = this.getScene().getRenderId();
  31558. if (this._preActivateId === sceneRenderId) {
  31559. return this;
  31560. }
  31561. this._preActivateId = sceneRenderId;
  31562. this._visibleInstances = null;
  31563. return this;
  31564. };
  31565. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31566. if (this._visibleInstances) {
  31567. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31568. }
  31569. return this;
  31570. };
  31571. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31572. if (!this._visibleInstances) {
  31573. this._visibleInstances = {};
  31574. this._visibleInstances.defaultRenderId = renderId;
  31575. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31576. }
  31577. if (!this._visibleInstances[renderId]) {
  31578. this._visibleInstances[renderId] = new Array();
  31579. }
  31580. this._visibleInstances[renderId].push(instance);
  31581. return this;
  31582. };
  31583. /**
  31584. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31585. * This means the mesh underlying bounding box and sphere are recomputed.
  31586. * Returns the Mesh.
  31587. */
  31588. Mesh.prototype.refreshBoundingInfo = function () {
  31589. return this._refreshBoundingInfo(false);
  31590. };
  31591. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31592. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31593. return this;
  31594. }
  31595. var data = this._getPositionData(applySkeleton);
  31596. if (data) {
  31597. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31598. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31599. }
  31600. if (this.subMeshes) {
  31601. for (var index = 0; index < this.subMeshes.length; index++) {
  31602. this.subMeshes[index].refreshBoundingInfo();
  31603. }
  31604. }
  31605. this._updateBoundingInfo();
  31606. return this;
  31607. };
  31608. Mesh.prototype._getPositionData = function (applySkeleton) {
  31609. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31610. if (data && applySkeleton && this.skeleton) {
  31611. data = BABYLON.Tools.Slice(data);
  31612. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31613. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31614. if (matricesWeightsData && matricesIndicesData) {
  31615. var needExtras = this.numBoneInfluencers > 4;
  31616. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31617. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31618. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31619. var tempVector = BABYLON.Tmp.Vector3[0];
  31620. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31621. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31622. var matWeightIdx = 0;
  31623. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31624. finalMatrix.reset();
  31625. var inf;
  31626. var weight;
  31627. for (inf = 0; inf < 4; inf++) {
  31628. weight = matricesWeightsData[matWeightIdx + inf];
  31629. if (weight > 0) {
  31630. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31631. finalMatrix.addToSelf(tempMatrix);
  31632. }
  31633. }
  31634. if (needExtras) {
  31635. for (inf = 0; inf < 4; inf++) {
  31636. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31637. if (weight > 0) {
  31638. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31639. finalMatrix.addToSelf(tempMatrix);
  31640. }
  31641. }
  31642. }
  31643. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31644. tempVector.toArray(data, index);
  31645. }
  31646. }
  31647. }
  31648. return data;
  31649. };
  31650. Mesh.prototype._createGlobalSubMesh = function (force) {
  31651. var totalVertices = this.getTotalVertices();
  31652. if (!totalVertices || !this.getIndices()) {
  31653. return null;
  31654. }
  31655. // Check if we need to recreate the submeshes
  31656. if (this.subMeshes && this.subMeshes.length > 0) {
  31657. var ib = this.getIndices();
  31658. if (!ib) {
  31659. return null;
  31660. }
  31661. var totalIndices = ib.length;
  31662. var needToRecreate = false;
  31663. if (force) {
  31664. needToRecreate = true;
  31665. }
  31666. else {
  31667. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31668. var submesh = _a[_i];
  31669. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31670. needToRecreate = true;
  31671. break;
  31672. }
  31673. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31674. needToRecreate = true;
  31675. break;
  31676. }
  31677. }
  31678. }
  31679. if (!needToRecreate) {
  31680. return this.subMeshes[0];
  31681. }
  31682. }
  31683. this.releaseSubMeshes();
  31684. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31685. };
  31686. Mesh.prototype.subdivide = function (count) {
  31687. if (count < 1) {
  31688. return;
  31689. }
  31690. var totalIndices = this.getTotalIndices();
  31691. var subdivisionSize = (totalIndices / count) | 0;
  31692. var offset = 0;
  31693. // Ensure that subdivisionSize is a multiple of 3
  31694. while (subdivisionSize % 3 !== 0) {
  31695. subdivisionSize++;
  31696. }
  31697. this.releaseSubMeshes();
  31698. for (var index = 0; index < count; index++) {
  31699. if (offset >= totalIndices) {
  31700. break;
  31701. }
  31702. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31703. offset += subdivisionSize;
  31704. }
  31705. this.synchronizeInstances();
  31706. };
  31707. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31708. if (updatable === void 0) { updatable = false; }
  31709. if (!this._geometry) {
  31710. var vertexData = new BABYLON.VertexData();
  31711. vertexData.set(data, kind);
  31712. var scene = this.getScene();
  31713. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31714. }
  31715. else {
  31716. this._geometry.setVerticesData(kind, data, updatable, stride);
  31717. }
  31718. return this;
  31719. };
  31720. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31721. if (updatable === void 0) { updatable = true; }
  31722. var vb = this.getVertexBuffer(kind);
  31723. if (!vb || vb.isUpdatable() === updatable) {
  31724. return;
  31725. }
  31726. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31727. };
  31728. /**
  31729. * Sets the mesh VertexBuffer.
  31730. * Returns the Mesh.
  31731. */
  31732. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31733. if (!this._geometry) {
  31734. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31735. }
  31736. this._geometry.setVerticesBuffer(buffer);
  31737. return this;
  31738. };
  31739. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31740. if (!this._geometry) {
  31741. return this;
  31742. }
  31743. if (!makeItUnique) {
  31744. this._geometry.updateVerticesData(kind, data, updateExtends);
  31745. }
  31746. else {
  31747. this.makeGeometryUnique();
  31748. this.updateVerticesData(kind, data, updateExtends, false);
  31749. }
  31750. return this;
  31751. };
  31752. /**
  31753. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31754. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31755. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31756. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31757. * Returns the Mesh.
  31758. */
  31759. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31760. if (computeNormals === void 0) { computeNormals = true; }
  31761. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31762. if (!positions) {
  31763. return this;
  31764. }
  31765. positionFunction(positions);
  31766. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31767. if (computeNormals) {
  31768. var indices = this.getIndices();
  31769. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31770. if (!normals) {
  31771. return this;
  31772. }
  31773. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31774. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31775. }
  31776. return this;
  31777. };
  31778. /**
  31779. * Creates a un-shared specific occurence of the geometry for the mesh.
  31780. * Returns the Mesh.
  31781. */
  31782. Mesh.prototype.makeGeometryUnique = function () {
  31783. if (!this._geometry) {
  31784. return this;
  31785. }
  31786. var oldGeometry = this._geometry;
  31787. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31788. oldGeometry.releaseForMesh(this, true);
  31789. geometry.applyToMesh(this);
  31790. return this;
  31791. };
  31792. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31793. if (totalVertices === void 0) { totalVertices = null; }
  31794. if (updatable === void 0) { updatable = false; }
  31795. if (!this._geometry) {
  31796. var vertexData = new BABYLON.VertexData();
  31797. vertexData.indices = indices;
  31798. var scene = this.getScene();
  31799. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31800. }
  31801. else {
  31802. this._geometry.setIndices(indices, totalVertices, updatable);
  31803. }
  31804. return this;
  31805. };
  31806. /**
  31807. * Update the current index buffer
  31808. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31809. * Returns the Mesh.
  31810. */
  31811. Mesh.prototype.updateIndices = function (indices, offset) {
  31812. if (!this._geometry) {
  31813. return this;
  31814. }
  31815. this._geometry.updateIndices(indices, offset);
  31816. return this;
  31817. };
  31818. /**
  31819. * Invert the geometry to move from a right handed system to a left handed one.
  31820. * Returns the Mesh.
  31821. */
  31822. Mesh.prototype.toLeftHanded = function () {
  31823. if (!this._geometry) {
  31824. return this;
  31825. }
  31826. this._geometry.toLeftHanded();
  31827. return this;
  31828. };
  31829. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31830. if (!this._geometry) {
  31831. return this;
  31832. }
  31833. var engine = this.getScene().getEngine();
  31834. // Wireframe
  31835. var indexToBind;
  31836. if (this._unIndexed) {
  31837. indexToBind = null;
  31838. }
  31839. else {
  31840. switch (fillMode) {
  31841. case BABYLON.Material.PointFillMode:
  31842. indexToBind = null;
  31843. break;
  31844. case BABYLON.Material.WireFrameFillMode:
  31845. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31846. break;
  31847. default:
  31848. case BABYLON.Material.TriangleFillMode:
  31849. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31850. break;
  31851. }
  31852. }
  31853. // VBOs
  31854. this._geometry._bind(effect, indexToBind);
  31855. return this;
  31856. };
  31857. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31858. if (alternate === void 0) { alternate = false; }
  31859. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31860. return this;
  31861. }
  31862. this.onBeforeDrawObservable.notifyObservers(this);
  31863. var scene = this.getScene();
  31864. var engine = scene.getEngine();
  31865. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31866. // or triangles as points
  31867. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31868. }
  31869. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31870. // Triangles as wireframe
  31871. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31872. }
  31873. else {
  31874. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31875. }
  31876. if (scene._isAlternateRenderingEnabled && !alternate) {
  31877. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31878. if (!effect || !scene.activeCamera) {
  31879. return this;
  31880. }
  31881. scene._switchToAlternateCameraConfiguration(true);
  31882. this._effectiveMaterial.bindView(effect);
  31883. this._effectiveMaterial.bindViewProjection(effect);
  31884. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31885. this._draw(subMesh, fillMode, instancesCount, true);
  31886. engine.setViewport(scene.activeCamera.viewport);
  31887. scene._switchToAlternateCameraConfiguration(false);
  31888. this._effectiveMaterial.bindView(effect);
  31889. this._effectiveMaterial.bindViewProjection(effect);
  31890. }
  31891. return this;
  31892. };
  31893. /**
  31894. * Registers for this mesh a javascript function called just before the rendering process.
  31895. * This function is passed the current mesh.
  31896. * Return the Mesh.
  31897. */
  31898. Mesh.prototype.registerBeforeRender = function (func) {
  31899. this.onBeforeRenderObservable.add(func);
  31900. return this;
  31901. };
  31902. /**
  31903. * Disposes a previously registered javascript function called before the rendering.
  31904. * This function is passed the current mesh.
  31905. * Returns the Mesh.
  31906. */
  31907. Mesh.prototype.unregisterBeforeRender = function (func) {
  31908. this.onBeforeRenderObservable.removeCallback(func);
  31909. return this;
  31910. };
  31911. /**
  31912. * Registers for this mesh a javascript function called just after the rendering is complete.
  31913. * This function is passed the current mesh.
  31914. * Returns the Mesh.
  31915. */
  31916. Mesh.prototype.registerAfterRender = function (func) {
  31917. this.onAfterRenderObservable.add(func);
  31918. return this;
  31919. };
  31920. /**
  31921. * Disposes a previously registered javascript function called after the rendering.
  31922. * This function is passed the current mesh.
  31923. * Return the Mesh.
  31924. */
  31925. Mesh.prototype.unregisterAfterRender = function (func) {
  31926. this.onAfterRenderObservable.removeCallback(func);
  31927. return this;
  31928. };
  31929. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31930. var scene = this.getScene();
  31931. this._batchCache.mustReturn = false;
  31932. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31933. this._batchCache.visibleInstances[subMeshId] = null;
  31934. if (this._visibleInstances) {
  31935. var currentRenderId = scene.getRenderId();
  31936. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31937. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31938. var selfRenderId = this._renderId;
  31939. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31940. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31941. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31942. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31943. }
  31944. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31945. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31946. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31947. this._batchCache.mustReturn = true;
  31948. return this._batchCache;
  31949. }
  31950. if (currentRenderId !== selfRenderId) {
  31951. this._batchCache.renderSelf[subMeshId] = false;
  31952. }
  31953. }
  31954. this._renderIdForInstances[subMeshId] = currentRenderId;
  31955. }
  31956. return this._batchCache;
  31957. };
  31958. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31959. var visibleInstances = batch.visibleInstances[subMesh._id];
  31960. if (!visibleInstances) {
  31961. return this;
  31962. }
  31963. var matricesCount = visibleInstances.length + 1;
  31964. var bufferSize = matricesCount * 16 * 4;
  31965. var currentInstancesBufferSize = this._instancesBufferSize;
  31966. var instancesBuffer = this._instancesBuffer;
  31967. while (this._instancesBufferSize < bufferSize) {
  31968. this._instancesBufferSize *= 2;
  31969. }
  31970. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31971. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31972. }
  31973. var offset = 0;
  31974. var instancesCount = 0;
  31975. var world = this.getWorldMatrix();
  31976. if (batch.renderSelf[subMesh._id]) {
  31977. world.copyToArray(this._instancesData, offset);
  31978. offset += 16;
  31979. instancesCount++;
  31980. }
  31981. if (visibleInstances) {
  31982. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31983. var instance = visibleInstances[instanceIndex];
  31984. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31985. offset += 16;
  31986. instancesCount++;
  31987. }
  31988. }
  31989. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31990. if (instancesBuffer) {
  31991. instancesBuffer.dispose();
  31992. }
  31993. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31994. this._instancesBuffer = instancesBuffer;
  31995. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31996. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31997. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31998. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31999. }
  32000. else {
  32001. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32002. }
  32003. this._bind(subMesh, effect, fillMode);
  32004. this._draw(subMesh, fillMode, instancesCount);
  32005. engine.unbindInstanceAttributes();
  32006. return this;
  32007. };
  32008. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32009. var scene = this.getScene();
  32010. var engine = scene.getEngine();
  32011. if (hardwareInstancedRendering) {
  32012. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32013. }
  32014. else {
  32015. if (batch.renderSelf[subMesh._id]) {
  32016. // Draw
  32017. if (onBeforeDraw) {
  32018. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32019. }
  32020. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32021. }
  32022. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32023. if (visibleInstancesForSubMesh) {
  32024. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32025. var instance = visibleInstancesForSubMesh[instanceIndex];
  32026. // World
  32027. var world = instance.getWorldMatrix();
  32028. if (onBeforeDraw) {
  32029. onBeforeDraw(true, world, effectiveMaterial);
  32030. }
  32031. // Draw
  32032. this._draw(subMesh, fillMode);
  32033. }
  32034. }
  32035. }
  32036. return this;
  32037. };
  32038. /**
  32039. * 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
  32040. * @param subMesh defines the subMesh to render
  32041. * @param enableAlphaMode defines if alpha mode can be changed
  32042. * @returns the current mesh
  32043. */
  32044. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32045. this._checkOcclusionQuery();
  32046. if (this._isOccluded) {
  32047. return this;
  32048. }
  32049. var scene = this.getScene();
  32050. // Managing instances
  32051. var batch = this._getInstancesRenderList(subMesh._id);
  32052. if (batch.mustReturn) {
  32053. return this;
  32054. }
  32055. // Checking geometry state
  32056. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32057. return this;
  32058. }
  32059. this.onBeforeRenderObservable.notifyObservers(this);
  32060. var engine = scene.getEngine();
  32061. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32062. // Material
  32063. var material = subMesh.getMaterial();
  32064. if (!material) {
  32065. return this;
  32066. }
  32067. this._effectiveMaterial = material;
  32068. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32069. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32070. return this;
  32071. }
  32072. }
  32073. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32074. return this;
  32075. }
  32076. // Alpha mode
  32077. if (enableAlphaMode) {
  32078. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32079. }
  32080. // Outline - step 1
  32081. var savedDepthWrite = engine.getDepthWrite();
  32082. if (this.renderOutline) {
  32083. engine.setDepthWrite(false);
  32084. scene.getOutlineRenderer().render(subMesh, batch);
  32085. engine.setDepthWrite(savedDepthWrite);
  32086. }
  32087. var effect;
  32088. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32089. effect = subMesh.effect;
  32090. }
  32091. else {
  32092. effect = this._effectiveMaterial.getEffect();
  32093. }
  32094. if (!effect) {
  32095. return this;
  32096. }
  32097. var sideOrientation = this.overrideMaterialSideOrientation;
  32098. if (sideOrientation == null) {
  32099. sideOrientation = this._effectiveMaterial.sideOrientation;
  32100. if (this._getWorldMatrixDeterminant() < 0) {
  32101. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32102. }
  32103. }
  32104. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32105. if (this._effectiveMaterial.forceDepthWrite) {
  32106. engine.setDepthWrite(true);
  32107. }
  32108. // Bind
  32109. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32110. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32111. this._bind(subMesh, effect, fillMode);
  32112. }
  32113. var world = this.getWorldMatrix();
  32114. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32115. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32116. }
  32117. else {
  32118. this._effectiveMaterial.bind(world, this);
  32119. }
  32120. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32121. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32122. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32123. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32124. }
  32125. // Draw
  32126. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32127. // Unbind
  32128. this._effectiveMaterial.unbind();
  32129. // Outline - step 2
  32130. if (this.renderOutline && savedDepthWrite) {
  32131. engine.setDepthWrite(true);
  32132. engine.setColorWrite(false);
  32133. scene.getOutlineRenderer().render(subMesh, batch);
  32134. engine.setColorWrite(true);
  32135. }
  32136. // Overlay
  32137. if (this.renderOverlay) {
  32138. var currentMode = engine.getAlphaMode();
  32139. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32140. scene.getOutlineRenderer().render(subMesh, batch, true);
  32141. engine.setAlphaMode(currentMode);
  32142. }
  32143. this.onAfterRenderObservable.notifyObservers(this);
  32144. return this;
  32145. };
  32146. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32147. if (isInstance && effectiveMaterial) {
  32148. effectiveMaterial.bindOnlyWorldMatrix(world);
  32149. }
  32150. };
  32151. /**
  32152. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32153. */
  32154. Mesh.prototype.getEmittedParticleSystems = function () {
  32155. var results = new Array();
  32156. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32157. var particleSystem = this.getScene().particleSystems[index];
  32158. if (particleSystem.emitter === this) {
  32159. results.push(particleSystem);
  32160. }
  32161. }
  32162. return results;
  32163. };
  32164. /**
  32165. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32166. */
  32167. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32168. var results = new Array();
  32169. var descendants = this.getDescendants();
  32170. descendants.push(this);
  32171. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32172. var particleSystem = this.getScene().particleSystems[index];
  32173. var emitter = particleSystem.emitter;
  32174. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32175. results.push(particleSystem);
  32176. }
  32177. }
  32178. return results;
  32179. };
  32180. /**
  32181. * Normalize matrix weights so that all vertices have a total weight set to 1
  32182. */
  32183. Mesh.prototype.cleanMatrixWeights = function () {
  32184. var epsilon = 1e-3;
  32185. var noInfluenceBoneIndex = 0.0;
  32186. if (this.skeleton) {
  32187. noInfluenceBoneIndex = this.skeleton.bones.length;
  32188. }
  32189. else {
  32190. return;
  32191. }
  32192. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32193. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32194. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32195. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32196. var influencers = this.numBoneInfluencers;
  32197. var size = matricesWeights.length;
  32198. for (var i = 0; i < size; i += 4) {
  32199. var weight = 0.0;
  32200. var firstZeroWeight = -1;
  32201. for (var j = 0; j < 4; j++) {
  32202. var w = matricesWeights[i + j];
  32203. weight += w;
  32204. if (w < epsilon && firstZeroWeight < 0) {
  32205. firstZeroWeight = j;
  32206. }
  32207. }
  32208. if (matricesWeightsExtra) {
  32209. for (var j = 0; j < 4; j++) {
  32210. var w = matricesWeightsExtra[i + j];
  32211. weight += w;
  32212. if (w < epsilon && firstZeroWeight < 0) {
  32213. firstZeroWeight = j + 4;
  32214. }
  32215. }
  32216. }
  32217. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32218. firstZeroWeight = influencers - 1;
  32219. }
  32220. if (weight > epsilon) {
  32221. var mweight = 1.0 / weight;
  32222. for (var j = 0; j < 4; j++) {
  32223. matricesWeights[i + j] *= mweight;
  32224. }
  32225. if (matricesWeightsExtra) {
  32226. for (var j = 0; j < 4; j++) {
  32227. matricesWeightsExtra[i + j] *= mweight;
  32228. }
  32229. }
  32230. }
  32231. else {
  32232. if (firstZeroWeight >= 4) {
  32233. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32234. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32235. }
  32236. else {
  32237. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32238. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32239. }
  32240. }
  32241. }
  32242. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32243. if (matricesIndicesExtra) {
  32244. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32245. }
  32246. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32247. if (matricesWeightsExtra) {
  32248. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32249. }
  32250. };
  32251. Mesh.prototype._checkDelayState = function () {
  32252. var scene = this.getScene();
  32253. if (this._geometry) {
  32254. this._geometry.load(scene);
  32255. }
  32256. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32257. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32258. this._queueLoad(scene);
  32259. }
  32260. return this;
  32261. };
  32262. Mesh.prototype._queueLoad = function (scene) {
  32263. var _this = this;
  32264. scene._addPendingData(this);
  32265. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32266. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32267. if (data instanceof ArrayBuffer) {
  32268. _this._delayLoadingFunction(data, _this);
  32269. }
  32270. else {
  32271. _this._delayLoadingFunction(JSON.parse(data), _this);
  32272. }
  32273. _this.instances.forEach(function (instance) {
  32274. instance._syncSubMeshes();
  32275. });
  32276. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32277. scene._removePendingData(_this);
  32278. }, function () { }, scene.database, getBinaryData);
  32279. return this;
  32280. };
  32281. /**
  32282. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32283. */
  32284. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32285. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32286. return false;
  32287. }
  32288. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32289. return false;
  32290. }
  32291. this._checkDelayState();
  32292. return true;
  32293. };
  32294. /**
  32295. * Sets the mesh material by the material or multiMaterial `id` property.
  32296. * The material `id` is a string identifying the material or the multiMaterial.
  32297. * This method returns the Mesh.
  32298. */
  32299. Mesh.prototype.setMaterialByID = function (id) {
  32300. var materials = this.getScene().materials;
  32301. var index;
  32302. for (index = materials.length - 1; index > -1; index--) {
  32303. if (materials[index].id === id) {
  32304. this.material = materials[index];
  32305. return this;
  32306. }
  32307. }
  32308. // Multi
  32309. var multiMaterials = this.getScene().multiMaterials;
  32310. for (index = multiMaterials.length - 1; index > -1; index--) {
  32311. if (multiMaterials[index].id === id) {
  32312. this.material = multiMaterials[index];
  32313. return this;
  32314. }
  32315. }
  32316. return this;
  32317. };
  32318. /**
  32319. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32320. */
  32321. Mesh.prototype.getAnimatables = function () {
  32322. var results = new Array();
  32323. if (this.material) {
  32324. results.push(this.material);
  32325. }
  32326. if (this.skeleton) {
  32327. results.push(this.skeleton);
  32328. }
  32329. return results;
  32330. };
  32331. /**
  32332. * Modifies the mesh geometry according to the passed transformation matrix.
  32333. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32334. * The mesh normals are modified accordingly the same transformation.
  32335. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32336. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32337. * Returns the Mesh.
  32338. */
  32339. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32340. // Position
  32341. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32342. return this;
  32343. }
  32344. var submeshes = this.subMeshes.splice(0);
  32345. this._resetPointsArrayCache();
  32346. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32347. var temp = new Array();
  32348. var index;
  32349. for (index = 0; index < data.length; index += 3) {
  32350. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32351. }
  32352. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32353. // Normals
  32354. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32355. return this;
  32356. }
  32357. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32358. temp = [];
  32359. for (index = 0; index < data.length; index += 3) {
  32360. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32361. }
  32362. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32363. // flip faces?
  32364. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32365. this.flipFaces();
  32366. }
  32367. // Restore submeshes
  32368. this.releaseSubMeshes();
  32369. this.subMeshes = submeshes;
  32370. return this;
  32371. };
  32372. /**
  32373. * Modifies the mesh geometry according to its own current World Matrix.
  32374. * The mesh World Matrix is then reset.
  32375. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32376. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32377. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32378. * Returns the Mesh.
  32379. */
  32380. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32381. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32382. this.scaling.copyFromFloats(1, 1, 1);
  32383. this.position.copyFromFloats(0, 0, 0);
  32384. this.rotation.copyFromFloats(0, 0, 0);
  32385. //only if quaternion is already set
  32386. if (this.rotationQuaternion) {
  32387. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32388. }
  32389. this._worldMatrix = BABYLON.Matrix.Identity();
  32390. return this;
  32391. };
  32392. Object.defineProperty(Mesh.prototype, "_positions", {
  32393. // Cache
  32394. get: function () {
  32395. if (this._geometry) {
  32396. return this._geometry._positions;
  32397. }
  32398. return null;
  32399. },
  32400. enumerable: true,
  32401. configurable: true
  32402. });
  32403. Mesh.prototype._resetPointsArrayCache = function () {
  32404. if (this._geometry) {
  32405. this._geometry._resetPointsArrayCache();
  32406. }
  32407. return this;
  32408. };
  32409. Mesh.prototype._generatePointsArray = function () {
  32410. if (this._geometry) {
  32411. return this._geometry._generatePointsArray();
  32412. }
  32413. return false;
  32414. };
  32415. /**
  32416. * Returns a new Mesh object generated from the current mesh properties.
  32417. * This method must not get confused with createInstance().
  32418. * The parameter `name` is a string, the name given to the new mesh.
  32419. * The optional parameter `newParent` can be any Node object (default `null`).
  32420. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32421. * 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.
  32422. */
  32423. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32424. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32425. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32426. };
  32427. /**
  32428. * Releases resources associated with this mesh.
  32429. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32430. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32431. */
  32432. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32433. var _this = this;
  32434. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32435. this.morphTargetManager = null;
  32436. if (this._geometry) {
  32437. this._geometry.releaseForMesh(this, true);
  32438. }
  32439. // Sources
  32440. var meshes = this.getScene().meshes;
  32441. meshes.forEach(function (abstractMesh) {
  32442. var mesh = abstractMesh;
  32443. if (mesh._source && mesh._source === _this) {
  32444. mesh._source = null;
  32445. }
  32446. });
  32447. this._source = null;
  32448. // Instances
  32449. if (this._instancesBuffer) {
  32450. this._instancesBuffer.dispose();
  32451. this._instancesBuffer = null;
  32452. }
  32453. while (this.instances.length) {
  32454. this.instances[0].dispose();
  32455. }
  32456. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32457. };
  32458. /**
  32459. * Modifies the mesh geometry according to a displacement map.
  32460. * 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.
  32461. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32462. * This method returns nothing.
  32463. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32464. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32465. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32466. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32467. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32468. *
  32469. * Returns the Mesh.
  32470. */
  32471. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32472. var _this = this;
  32473. var scene = this.getScene();
  32474. var onload = function (img) {
  32475. // Getting height map data
  32476. var canvas = document.createElement("canvas");
  32477. var context = canvas.getContext("2d");
  32478. var heightMapWidth = img.width;
  32479. var heightMapHeight = img.height;
  32480. canvas.width = heightMapWidth;
  32481. canvas.height = heightMapHeight;
  32482. context.drawImage(img, 0, 0);
  32483. // Create VertexData from map data
  32484. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32485. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32486. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32487. //execute success callback, if set
  32488. if (onSuccess) {
  32489. onSuccess(_this);
  32490. }
  32491. };
  32492. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32493. return this;
  32494. };
  32495. /**
  32496. * Modifies the mesh geometry according to a displacementMap buffer.
  32497. * 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.
  32498. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32499. * This method returns nothing.
  32500. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32501. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32502. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32503. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32504. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32505. *
  32506. * Returns the Mesh.
  32507. */
  32508. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32509. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32510. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32511. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32512. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32513. return this;
  32514. }
  32515. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32516. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32517. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32518. var position = BABYLON.Vector3.Zero();
  32519. var normal = BABYLON.Vector3.Zero();
  32520. var uv = BABYLON.Vector2.Zero();
  32521. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32522. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32523. for (var index = 0; index < positions.length; index += 3) {
  32524. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32525. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32526. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32527. // Compute height
  32528. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32529. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32530. var pos = (u + v * heightMapWidth) * 4;
  32531. var r = buffer[pos] / 255.0;
  32532. var g = buffer[pos + 1] / 255.0;
  32533. var b = buffer[pos + 2] / 255.0;
  32534. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32535. normal.normalize();
  32536. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32537. position = position.add(normal);
  32538. position.toArray(positions, index);
  32539. }
  32540. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32541. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32542. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32543. return this;
  32544. };
  32545. /**
  32546. * Modify the mesh to get a flat shading rendering.
  32547. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32548. * This method returns the Mesh.
  32549. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32550. */
  32551. Mesh.prototype.convertToFlatShadedMesh = function () {
  32552. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32553. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32554. var kinds = this.getVerticesDataKinds();
  32555. var vbs = {};
  32556. var data = {};
  32557. var newdata = {};
  32558. var updatableNormals = false;
  32559. var kindIndex;
  32560. var kind;
  32561. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32562. kind = kinds[kindIndex];
  32563. var vertexBuffer = this.getVertexBuffer(kind);
  32564. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32565. updatableNormals = vertexBuffer.isUpdatable();
  32566. kinds.splice(kindIndex, 1);
  32567. kindIndex--;
  32568. continue;
  32569. }
  32570. vbs[kind] = vertexBuffer;
  32571. data[kind] = vbs[kind].getData();
  32572. newdata[kind] = [];
  32573. }
  32574. // Save previous submeshes
  32575. var previousSubmeshes = this.subMeshes.slice(0);
  32576. var indices = this.getIndices();
  32577. var totalIndices = this.getTotalIndices();
  32578. // Generating unique vertices per face
  32579. var index;
  32580. for (index = 0; index < totalIndices; index++) {
  32581. var vertexIndex = indices[index];
  32582. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32583. kind = kinds[kindIndex];
  32584. var stride = vbs[kind].getStrideSize();
  32585. for (var offset = 0; offset < stride; offset++) {
  32586. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32587. }
  32588. }
  32589. }
  32590. // Updating faces & normal
  32591. var normals = [];
  32592. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32593. for (index = 0; index < totalIndices; index += 3) {
  32594. indices[index] = index;
  32595. indices[index + 1] = index + 1;
  32596. indices[index + 2] = index + 2;
  32597. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32598. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32599. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32600. var p1p2 = p1.subtract(p2);
  32601. var p3p2 = p3.subtract(p2);
  32602. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32603. // Store same normals for every vertex
  32604. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32605. normals.push(normal.x);
  32606. normals.push(normal.y);
  32607. normals.push(normal.z);
  32608. }
  32609. }
  32610. this.setIndices(indices);
  32611. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32612. // Updating vertex buffers
  32613. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32614. kind = kinds[kindIndex];
  32615. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32616. }
  32617. // Updating submeshes
  32618. this.releaseSubMeshes();
  32619. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32620. var previousOne = previousSubmeshes[submeshIndex];
  32621. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32622. }
  32623. this.synchronizeInstances();
  32624. return this;
  32625. };
  32626. /**
  32627. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32628. * In other words, more vertices, no more indices and a single bigger VBO.
  32629. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32630. * Returns the Mesh.
  32631. */
  32632. Mesh.prototype.convertToUnIndexedMesh = function () {
  32633. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32634. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32635. var kinds = this.getVerticesDataKinds();
  32636. var vbs = {};
  32637. var data = {};
  32638. var newdata = {};
  32639. var kindIndex;
  32640. var kind;
  32641. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32642. kind = kinds[kindIndex];
  32643. var vertexBuffer = this.getVertexBuffer(kind);
  32644. vbs[kind] = vertexBuffer;
  32645. data[kind] = vbs[kind].getData();
  32646. newdata[kind] = [];
  32647. }
  32648. // Save previous submeshes
  32649. var previousSubmeshes = this.subMeshes.slice(0);
  32650. var indices = this.getIndices();
  32651. var totalIndices = this.getTotalIndices();
  32652. // Generating unique vertices per face
  32653. var index;
  32654. for (index = 0; index < totalIndices; index++) {
  32655. var vertexIndex = indices[index];
  32656. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32657. kind = kinds[kindIndex];
  32658. var stride = vbs[kind].getStrideSize();
  32659. for (var offset = 0; offset < stride; offset++) {
  32660. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32661. }
  32662. }
  32663. }
  32664. // Updating indices
  32665. for (index = 0; index < totalIndices; index += 3) {
  32666. indices[index] = index;
  32667. indices[index + 1] = index + 1;
  32668. indices[index + 2] = index + 2;
  32669. }
  32670. this.setIndices(indices);
  32671. // Updating vertex buffers
  32672. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32673. kind = kinds[kindIndex];
  32674. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32675. }
  32676. // Updating submeshes
  32677. this.releaseSubMeshes();
  32678. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32679. var previousOne = previousSubmeshes[submeshIndex];
  32680. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32681. }
  32682. this._unIndexed = true;
  32683. this.synchronizeInstances();
  32684. return this;
  32685. };
  32686. /**
  32687. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32688. * This method returns the Mesh.
  32689. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32690. */
  32691. Mesh.prototype.flipFaces = function (flipNormals) {
  32692. if (flipNormals === void 0) { flipNormals = false; }
  32693. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32694. var i;
  32695. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32696. for (i = 0; i < vertex_data.normals.length; i++) {
  32697. vertex_data.normals[i] *= -1;
  32698. }
  32699. }
  32700. if (vertex_data.indices) {
  32701. var temp;
  32702. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32703. // reassign indices
  32704. temp = vertex_data.indices[i + 1];
  32705. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32706. vertex_data.indices[i + 2] = temp;
  32707. }
  32708. }
  32709. vertex_data.applyToMesh(this);
  32710. return this;
  32711. };
  32712. // Instances
  32713. /**
  32714. * Creates a new InstancedMesh object from the mesh model.
  32715. * An instance shares the same properties and the same material than its model.
  32716. * Only these properties of each instance can then be set individually :
  32717. * - position
  32718. * - rotation
  32719. * - rotationQuaternion
  32720. * - setPivotMatrix
  32721. * - scaling
  32722. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32723. * Warning : this method is not supported for Line mesh and LineSystem
  32724. */
  32725. Mesh.prototype.createInstance = function (name) {
  32726. return new BABYLON.InstancedMesh(name, this);
  32727. };
  32728. /**
  32729. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32730. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32731. * This method returns the Mesh.
  32732. */
  32733. Mesh.prototype.synchronizeInstances = function () {
  32734. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32735. var instance = this.instances[instanceIndex];
  32736. instance._syncSubMeshes();
  32737. }
  32738. return this;
  32739. };
  32740. /**
  32741. * Simplify the mesh according to the given array of settings.
  32742. * Function will return immediately and will simplify async. It returns the Mesh.
  32743. * @param settings a collection of simplification settings.
  32744. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32745. * @param type the type of simplification to run.
  32746. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32747. */
  32748. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32749. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32750. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32751. this.getScene().simplificationQueue.addTask({
  32752. settings: settings,
  32753. parallelProcessing: parallelProcessing,
  32754. mesh: this,
  32755. simplificationType: simplificationType,
  32756. successCallback: successCallback
  32757. });
  32758. return this;
  32759. };
  32760. /**
  32761. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32762. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32763. * This should be used together with the simplification to avoid disappearing triangles.
  32764. * Returns the Mesh.
  32765. * @param successCallback an optional success callback to be called after the optimization finished.
  32766. */
  32767. Mesh.prototype.optimizeIndices = function (successCallback) {
  32768. var _this = this;
  32769. var indices = this.getIndices();
  32770. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32771. if (!positions || !indices) {
  32772. return this;
  32773. }
  32774. var vectorPositions = new Array();
  32775. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32776. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32777. }
  32778. var dupes = new Array();
  32779. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32780. var realPos = vectorPositions.length - 1 - iteration;
  32781. var testedPosition = vectorPositions[realPos];
  32782. for (var j = 0; j < realPos; ++j) {
  32783. var againstPosition = vectorPositions[j];
  32784. if (testedPosition.equals(againstPosition)) {
  32785. dupes[realPos] = j;
  32786. break;
  32787. }
  32788. }
  32789. }, function () {
  32790. for (var i = 0; i < indices.length; ++i) {
  32791. indices[i] = dupes[indices[i]] || indices[i];
  32792. }
  32793. //indices are now reordered
  32794. var originalSubMeshes = _this.subMeshes.slice(0);
  32795. _this.setIndices(indices);
  32796. _this.subMeshes = originalSubMeshes;
  32797. if (successCallback) {
  32798. successCallback(_this);
  32799. }
  32800. });
  32801. return this;
  32802. };
  32803. Mesh.prototype.serialize = function (serializationObject) {
  32804. serializationObject.name = this.name;
  32805. serializationObject.id = this.id;
  32806. serializationObject.type = this.getClassName();
  32807. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32808. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32809. }
  32810. serializationObject.position = this.position.asArray();
  32811. if (this.rotationQuaternion) {
  32812. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32813. }
  32814. else if (this.rotation) {
  32815. serializationObject.rotation = this.rotation.asArray();
  32816. }
  32817. serializationObject.scaling = this.scaling.asArray();
  32818. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32819. serializationObject.isEnabled = this.isEnabled(false);
  32820. serializationObject.isVisible = this.isVisible;
  32821. serializationObject.infiniteDistance = this.infiniteDistance;
  32822. serializationObject.pickable = this.isPickable;
  32823. serializationObject.receiveShadows = this.receiveShadows;
  32824. serializationObject.billboardMode = this.billboardMode;
  32825. serializationObject.visibility = this.visibility;
  32826. serializationObject.checkCollisions = this.checkCollisions;
  32827. serializationObject.isBlocker = this.isBlocker;
  32828. // Parent
  32829. if (this.parent) {
  32830. serializationObject.parentId = this.parent.id;
  32831. }
  32832. // Geometry
  32833. serializationObject.isUnIndexed = this.isUnIndexed;
  32834. var geometry = this._geometry;
  32835. if (geometry) {
  32836. var geometryId = geometry.id;
  32837. serializationObject.geometryId = geometryId;
  32838. // SubMeshes
  32839. serializationObject.subMeshes = [];
  32840. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32841. var subMesh = this.subMeshes[subIndex];
  32842. serializationObject.subMeshes.push({
  32843. materialIndex: subMesh.materialIndex,
  32844. verticesStart: subMesh.verticesStart,
  32845. verticesCount: subMesh.verticesCount,
  32846. indexStart: subMesh.indexStart,
  32847. indexCount: subMesh.indexCount
  32848. });
  32849. }
  32850. }
  32851. // Material
  32852. if (this.material) {
  32853. serializationObject.materialId = this.material.id;
  32854. }
  32855. else {
  32856. this.material = null;
  32857. }
  32858. // Morph targets
  32859. if (this.morphTargetManager) {
  32860. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32861. }
  32862. // Skeleton
  32863. if (this.skeleton) {
  32864. serializationObject.skeletonId = this.skeleton.id;
  32865. }
  32866. // Physics
  32867. //TODO implement correct serialization for physics impostors.
  32868. var impostor = this.getPhysicsImpostor();
  32869. if (impostor) {
  32870. serializationObject.physicsMass = impostor.getParam("mass");
  32871. serializationObject.physicsFriction = impostor.getParam("friction");
  32872. serializationObject.physicsRestitution = impostor.getParam("mass");
  32873. serializationObject.physicsImpostor = impostor.type;
  32874. }
  32875. // Metadata
  32876. if (this.metadata) {
  32877. serializationObject.metadata = this.metadata;
  32878. }
  32879. // Instances
  32880. serializationObject.instances = [];
  32881. for (var index = 0; index < this.instances.length; index++) {
  32882. var instance = this.instances[index];
  32883. var serializationInstance = {
  32884. name: instance.name,
  32885. id: instance.id,
  32886. position: instance.position.asArray(),
  32887. scaling: instance.scaling.asArray()
  32888. };
  32889. if (instance.rotationQuaternion) {
  32890. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32891. }
  32892. else if (instance.rotation) {
  32893. serializationInstance.rotation = instance.rotation.asArray();
  32894. }
  32895. serializationObject.instances.push(serializationInstance);
  32896. // Animations
  32897. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32898. serializationInstance.ranges = instance.serializeAnimationRanges();
  32899. }
  32900. //
  32901. // Animations
  32902. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32903. serializationObject.ranges = this.serializeAnimationRanges();
  32904. // Layer mask
  32905. serializationObject.layerMask = this.layerMask;
  32906. // Alpha
  32907. serializationObject.alphaIndex = this.alphaIndex;
  32908. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32909. // Overlay
  32910. serializationObject.overlayAlpha = this.overlayAlpha;
  32911. serializationObject.overlayColor = this.overlayColor.asArray();
  32912. serializationObject.renderOverlay = this.renderOverlay;
  32913. // Fog
  32914. serializationObject.applyFog = this.applyFog;
  32915. // Action Manager
  32916. if (this.actionManager) {
  32917. serializationObject.actions = this.actionManager.serialize(this.name);
  32918. }
  32919. };
  32920. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32921. if (!this.geometry) {
  32922. return;
  32923. }
  32924. this._markSubMeshesAsAttributesDirty();
  32925. var morphTargetManager = this._morphTargetManager;
  32926. if (morphTargetManager && morphTargetManager.vertexCount) {
  32927. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32928. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32929. this.morphTargetManager = null;
  32930. return;
  32931. }
  32932. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32933. var morphTarget = morphTargetManager.getActiveTarget(index);
  32934. var positions = morphTarget.getPositions();
  32935. if (!positions) {
  32936. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32937. return;
  32938. }
  32939. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32940. var normals = morphTarget.getNormals();
  32941. if (normals) {
  32942. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32943. }
  32944. var tangents = morphTarget.getTangents();
  32945. if (tangents) {
  32946. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32947. }
  32948. }
  32949. }
  32950. else {
  32951. var index = 0;
  32952. // Positions
  32953. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32954. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32955. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32956. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32957. }
  32958. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32959. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32960. }
  32961. index++;
  32962. }
  32963. }
  32964. };
  32965. // Statics
  32966. /**
  32967. * Returns a new Mesh object parsed from the source provided.
  32968. * The parameter `parsedMesh` is the source.
  32969. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32970. */
  32971. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32972. var mesh;
  32973. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32974. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32975. }
  32976. else {
  32977. mesh = new Mesh(parsedMesh.name, scene);
  32978. }
  32979. mesh.id = parsedMesh.id;
  32980. if (BABYLON.Tags) {
  32981. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32982. }
  32983. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32984. if (parsedMesh.metadata !== undefined) {
  32985. mesh.metadata = parsedMesh.metadata;
  32986. }
  32987. if (parsedMesh.rotationQuaternion) {
  32988. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32989. }
  32990. else if (parsedMesh.rotation) {
  32991. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32992. }
  32993. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32994. if (parsedMesh.localMatrix) {
  32995. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32996. }
  32997. else if (parsedMesh.pivotMatrix) {
  32998. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32999. }
  33000. mesh.setEnabled(parsedMesh.isEnabled);
  33001. mesh.isVisible = parsedMesh.isVisible;
  33002. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33003. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33004. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33005. if (parsedMesh.applyFog !== undefined) {
  33006. mesh.applyFog = parsedMesh.applyFog;
  33007. }
  33008. if (parsedMesh.pickable !== undefined) {
  33009. mesh.isPickable = parsedMesh.pickable;
  33010. }
  33011. if (parsedMesh.alphaIndex !== undefined) {
  33012. mesh.alphaIndex = parsedMesh.alphaIndex;
  33013. }
  33014. mesh.receiveShadows = parsedMesh.receiveShadows;
  33015. mesh.billboardMode = parsedMesh.billboardMode;
  33016. if (parsedMesh.visibility !== undefined) {
  33017. mesh.visibility = parsedMesh.visibility;
  33018. }
  33019. mesh.checkCollisions = parsedMesh.checkCollisions;
  33020. if (parsedMesh.isBlocker !== undefined) {
  33021. mesh.isBlocker = parsedMesh.isBlocker;
  33022. }
  33023. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33024. // freezeWorldMatrix
  33025. if (parsedMesh.freezeWorldMatrix) {
  33026. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33027. }
  33028. // Parent
  33029. if (parsedMesh.parentId) {
  33030. mesh._waitingParentId = parsedMesh.parentId;
  33031. }
  33032. // Actions
  33033. if (parsedMesh.actions !== undefined) {
  33034. mesh._waitingActions = parsedMesh.actions;
  33035. }
  33036. // Overlay
  33037. if (parsedMesh.overlayAlpha !== undefined) {
  33038. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33039. }
  33040. if (parsedMesh.overlayColor !== undefined) {
  33041. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33042. }
  33043. if (parsedMesh.renderOverlay !== undefined) {
  33044. mesh.renderOverlay = parsedMesh.renderOverlay;
  33045. }
  33046. // Geometry
  33047. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33048. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33049. if (parsedMesh.delayLoadingFile) {
  33050. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33051. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33052. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33053. if (parsedMesh._binaryInfo) {
  33054. mesh._binaryInfo = parsedMesh._binaryInfo;
  33055. }
  33056. mesh._delayInfo = [];
  33057. if (parsedMesh.hasUVs) {
  33058. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33059. }
  33060. if (parsedMesh.hasUVs2) {
  33061. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33062. }
  33063. if (parsedMesh.hasUVs3) {
  33064. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33065. }
  33066. if (parsedMesh.hasUVs4) {
  33067. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33068. }
  33069. if (parsedMesh.hasUVs5) {
  33070. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33071. }
  33072. if (parsedMesh.hasUVs6) {
  33073. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33074. }
  33075. if (parsedMesh.hasColors) {
  33076. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33077. }
  33078. if (parsedMesh.hasMatricesIndices) {
  33079. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33080. }
  33081. if (parsedMesh.hasMatricesWeights) {
  33082. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33083. }
  33084. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33085. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33086. mesh._checkDelayState();
  33087. }
  33088. }
  33089. else {
  33090. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33091. }
  33092. // Material
  33093. if (parsedMesh.materialId) {
  33094. mesh.setMaterialByID(parsedMesh.materialId);
  33095. }
  33096. else {
  33097. mesh.material = null;
  33098. }
  33099. // Morph targets
  33100. if (parsedMesh.morphTargetManagerId > -1) {
  33101. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33102. }
  33103. // Skeleton
  33104. if (parsedMesh.skeletonId > -1) {
  33105. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33106. if (parsedMesh.numBoneInfluencers) {
  33107. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33108. }
  33109. }
  33110. // Animations
  33111. if (parsedMesh.animations) {
  33112. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33113. var parsedAnimation = parsedMesh.animations[animationIndex];
  33114. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33115. }
  33116. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33117. }
  33118. if (parsedMesh.autoAnimate) {
  33119. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33120. }
  33121. // Layer Mask
  33122. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33123. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33124. }
  33125. else {
  33126. mesh.layerMask = 0x0FFFFFFF;
  33127. }
  33128. // Physics
  33129. if (parsedMesh.physicsImpostor) {
  33130. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33131. mass: parsedMesh.physicsMass,
  33132. friction: parsedMesh.physicsFriction,
  33133. restitution: parsedMesh.physicsRestitution
  33134. }, scene);
  33135. }
  33136. // Instances
  33137. if (parsedMesh.instances) {
  33138. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33139. var parsedInstance = parsedMesh.instances[index];
  33140. var instance = mesh.createInstance(parsedInstance.name);
  33141. if (parsedInstance.id) {
  33142. instance.id = parsedInstance.id;
  33143. }
  33144. if (BABYLON.Tags) {
  33145. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33146. }
  33147. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33148. if (parsedInstance.parentId) {
  33149. instance._waitingParentId = parsedInstance.parentId;
  33150. }
  33151. if (parsedInstance.rotationQuaternion) {
  33152. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33153. }
  33154. else if (parsedInstance.rotation) {
  33155. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33156. }
  33157. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33158. instance.checkCollisions = mesh.checkCollisions;
  33159. if (parsedMesh.animations) {
  33160. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33161. parsedAnimation = parsedMesh.animations[animationIndex];
  33162. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33163. }
  33164. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33165. if (parsedMesh.autoAnimate) {
  33166. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33167. }
  33168. }
  33169. }
  33170. }
  33171. return mesh;
  33172. };
  33173. /**
  33174. * Creates a ribbon mesh.
  33175. * Please consider using the same method from the MeshBuilder class instead.
  33176. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33177. *
  33178. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33179. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33180. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33181. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33182. * 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.
  33183. * 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.
  33184. * 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
  33185. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33186. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33188. */
  33189. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33190. if (closeArray === void 0) { closeArray = false; }
  33191. if (updatable === void 0) { updatable = false; }
  33192. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33193. pathArray: pathArray,
  33194. closeArray: closeArray,
  33195. closePath: closePath,
  33196. offset: offset,
  33197. updatable: updatable,
  33198. sideOrientation: sideOrientation,
  33199. instance: instance
  33200. }, scene);
  33201. };
  33202. /**
  33203. * Creates a plane polygonal mesh. By default, this is a disc.
  33204. * Please consider using the same method from the MeshBuilder class instead.
  33205. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33206. * 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.
  33207. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33208. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33210. */
  33211. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33212. if (scene === void 0) { scene = null; }
  33213. var options = {
  33214. radius: radius,
  33215. tessellation: tessellation,
  33216. sideOrientation: sideOrientation,
  33217. updatable: updatable
  33218. };
  33219. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33220. };
  33221. /**
  33222. * Creates a box mesh.
  33223. * Please consider using the same method from the MeshBuilder class instead.
  33224. * The parameter `size` sets the size (float) of each box side (default 1).
  33225. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33226. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33227. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33228. */
  33229. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33230. if (scene === void 0) { scene = null; }
  33231. var options = {
  33232. size: size,
  33233. sideOrientation: sideOrientation,
  33234. updatable: updatable
  33235. };
  33236. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33237. };
  33238. /**
  33239. * Creates a sphere mesh.
  33240. * Please consider using the same method from the MeshBuilder class instead.
  33241. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33242. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33243. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33244. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33246. */
  33247. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33248. var options = {
  33249. segments: segments,
  33250. diameterX: diameter,
  33251. diameterY: diameter,
  33252. diameterZ: diameter,
  33253. sideOrientation: sideOrientation,
  33254. updatable: updatable
  33255. };
  33256. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33257. };
  33258. /**
  33259. * Creates a cylinder or a cone mesh.
  33260. * Please consider using the same method from the MeshBuilder class instead.
  33261. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33262. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33263. * 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.
  33264. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33265. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33266. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33267. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33268. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33269. */
  33270. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33271. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33272. if (scene !== undefined) {
  33273. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33274. updatable = scene;
  33275. }
  33276. scene = subdivisions;
  33277. subdivisions = 1;
  33278. }
  33279. var options = {
  33280. height: height,
  33281. diameterTop: diameterTop,
  33282. diameterBottom: diameterBottom,
  33283. tessellation: tessellation,
  33284. subdivisions: subdivisions,
  33285. sideOrientation: sideOrientation,
  33286. updatable: updatable
  33287. };
  33288. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33289. };
  33290. // Torus (Code from SharpDX.org)
  33291. /**
  33292. * Creates a torus mesh.
  33293. * Please consider using the same method from the MeshBuilder class instead.
  33294. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33295. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33296. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33297. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33298. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33300. */
  33301. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33302. var options = {
  33303. diameter: diameter,
  33304. thickness: thickness,
  33305. tessellation: tessellation,
  33306. sideOrientation: sideOrientation,
  33307. updatable: updatable
  33308. };
  33309. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33310. };
  33311. /**
  33312. * Creates a torus knot mesh.
  33313. * Please consider using the same method from the MeshBuilder class instead.
  33314. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33315. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33316. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33317. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33318. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33319. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33321. */
  33322. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33323. var options = {
  33324. radius: radius,
  33325. tube: tube,
  33326. radialSegments: radialSegments,
  33327. tubularSegments: tubularSegments,
  33328. p: p,
  33329. q: q,
  33330. sideOrientation: sideOrientation,
  33331. updatable: updatable
  33332. };
  33333. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33334. };
  33335. /**
  33336. * Creates a line mesh.
  33337. * Please consider using the same method from the MeshBuilder class instead.
  33338. * 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.
  33339. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33340. * The parameter `points` is an array successive Vector3.
  33341. * 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
  33342. * When updating an instance, remember that only point positions can change, not the number of points.
  33343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33344. */
  33345. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33346. if (scene === void 0) { scene = null; }
  33347. if (updatable === void 0) { updatable = false; }
  33348. if (instance === void 0) { instance = null; }
  33349. var options = {
  33350. points: points,
  33351. updatable: updatable,
  33352. instance: instance
  33353. };
  33354. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33355. };
  33356. /**
  33357. * Creates a dashed line mesh.
  33358. * Please consider using the same method from the MeshBuilder class instead.
  33359. * 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.
  33360. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33361. * The parameter `points` is an array successive Vector3.
  33362. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33363. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33364. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33365. * 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
  33366. * When updating an instance, remember that only point positions can change, not the number of points.
  33367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33368. */
  33369. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33370. if (scene === void 0) { scene = null; }
  33371. var options = {
  33372. points: points,
  33373. dashSize: dashSize,
  33374. gapSize: gapSize,
  33375. dashNb: dashNb,
  33376. updatable: updatable,
  33377. instance: instance
  33378. };
  33379. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33380. };
  33381. /**
  33382. * Creates a polygon mesh.
  33383. * Please consider using the same method from the MeshBuilder class instead.
  33384. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33385. * 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.
  33386. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33387. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33388. * Remember you can only change the shape positions, not their number when updating a polygon.
  33389. */
  33390. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33391. var options = {
  33392. shape: shape,
  33393. holes: holes,
  33394. updatable: updatable,
  33395. sideOrientation: sideOrientation
  33396. };
  33397. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33398. };
  33399. /**
  33400. * Creates an extruded polygon mesh, with depth in the Y direction.
  33401. * Please consider using the same method from the MeshBuilder class instead.
  33402. */
  33403. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33404. var options = {
  33405. shape: shape,
  33406. holes: holes,
  33407. depth: depth,
  33408. updatable: updatable,
  33409. sideOrientation: sideOrientation
  33410. };
  33411. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33412. };
  33413. /**
  33414. * Creates an extruded shape mesh.
  33415. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33416. * Please consider using the same method from the MeshBuilder class instead.
  33417. *
  33418. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33419. * 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
  33420. * extruded along the Z axis.
  33421. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33422. * 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.
  33423. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33424. * 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
  33425. * 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
  33426. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33428. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33430. */
  33431. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33432. if (scene === void 0) { scene = null; }
  33433. var options = {
  33434. shape: shape,
  33435. path: path,
  33436. scale: scale,
  33437. rotation: rotation,
  33438. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33439. sideOrientation: sideOrientation,
  33440. instance: instance,
  33441. updatable: updatable
  33442. };
  33443. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33444. };
  33445. /**
  33446. * Creates an custom extruded shape mesh.
  33447. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33448. * Please consider using the same method from the MeshBuilder class instead.
  33449. *
  33450. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33451. * 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
  33452. * extruded along the Z axis.
  33453. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33454. * 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
  33455. * and the distance of this point from the begining of the path :
  33456. * ```javascript
  33457. * var rotationFunction = function(i, distance) {
  33458. * // do things
  33459. * return rotationValue; }
  33460. * ```
  33461. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33462. * 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
  33463. * and the distance of this point from the begining of the path :
  33464. * ```javascript
  33465. * var scaleFunction = function(i, distance) {
  33466. * // do things
  33467. * return scaleValue;}
  33468. * ```
  33469. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33470. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33471. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33472. * 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
  33473. * 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
  33474. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33475. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33476. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33478. */
  33479. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33480. var options = {
  33481. shape: shape,
  33482. path: path,
  33483. scaleFunction: scaleFunction,
  33484. rotationFunction: rotationFunction,
  33485. ribbonCloseArray: ribbonCloseArray,
  33486. ribbonClosePath: ribbonClosePath,
  33487. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33488. sideOrientation: sideOrientation,
  33489. instance: instance,
  33490. updatable: updatable
  33491. };
  33492. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33493. };
  33494. /**
  33495. * Creates lathe mesh.
  33496. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33497. * Please consider using the same method from the MeshBuilder class instead.
  33498. * 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
  33499. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33500. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33501. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33503. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33505. */
  33506. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33507. var options = {
  33508. shape: shape,
  33509. radius: radius,
  33510. tessellation: tessellation,
  33511. sideOrientation: sideOrientation,
  33512. updatable: updatable
  33513. };
  33514. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33515. };
  33516. /**
  33517. * Creates a plane mesh.
  33518. * Please consider using the same method from the MeshBuilder class instead.
  33519. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33520. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33521. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33523. */
  33524. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33525. var options = {
  33526. size: size,
  33527. width: size,
  33528. height: size,
  33529. sideOrientation: sideOrientation,
  33530. updatable: updatable
  33531. };
  33532. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33533. };
  33534. /**
  33535. * Creates a ground mesh.
  33536. * Please consider using the same method from the MeshBuilder class instead.
  33537. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33538. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33540. */
  33541. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33542. var options = {
  33543. width: width,
  33544. height: height,
  33545. subdivisions: subdivisions,
  33546. updatable: updatable
  33547. };
  33548. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33549. };
  33550. /**
  33551. * Creates a tiled ground mesh.
  33552. * Please consider using the same method from the MeshBuilder class instead.
  33553. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33554. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33555. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33556. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33557. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33558. * numbers of subdivisions on the ground width and height of each tile.
  33559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33560. */
  33561. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33562. var options = {
  33563. xmin: xmin,
  33564. zmin: zmin,
  33565. xmax: xmax,
  33566. zmax: zmax,
  33567. subdivisions: subdivisions,
  33568. precision: precision,
  33569. updatable: updatable
  33570. };
  33571. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33572. };
  33573. /**
  33574. * Creates a ground mesh from a height map.
  33575. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33576. * Please consider using the same method from the MeshBuilder class instead.
  33577. * The parameter `url` sets the URL of the height map image resource.
  33578. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33579. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33580. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33581. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33582. * 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).
  33583. * This function is passed the newly built mesh :
  33584. * ```javascript
  33585. * function(mesh) { // do things
  33586. * return; }
  33587. * ```
  33588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33589. */
  33590. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33591. var options = {
  33592. width: width,
  33593. height: height,
  33594. subdivisions: subdivisions,
  33595. minHeight: minHeight,
  33596. maxHeight: maxHeight,
  33597. updatable: updatable,
  33598. onReady: onReady
  33599. };
  33600. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33601. };
  33602. /**
  33603. * Creates a tube mesh.
  33604. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33605. * Please consider using the same method from the MeshBuilder class instead.
  33606. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33607. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33608. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33609. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33610. * 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.
  33611. * It must return a radius value (positive float) :
  33612. * ```javascript
  33613. * var radiusFunction = function(i, distance) {
  33614. * // do things
  33615. * return radius; }
  33616. * ```
  33617. * 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
  33618. * 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
  33619. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33620. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33622. */
  33623. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33624. var options = {
  33625. path: path,
  33626. radius: radius,
  33627. tessellation: tessellation,
  33628. radiusFunction: radiusFunction,
  33629. arc: 1,
  33630. cap: cap,
  33631. updatable: updatable,
  33632. sideOrientation: sideOrientation,
  33633. instance: instance
  33634. };
  33635. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33636. };
  33637. /**
  33638. * Creates a polyhedron mesh.
  33639. * Please consider using the same method from the MeshBuilder class instead.
  33640. * 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
  33641. * to choose the wanted type.
  33642. * The parameter `size` (positive float, default 1) sets the polygon size.
  33643. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33644. * 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`.
  33645. * 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
  33646. * 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)`).
  33647. * 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
  33648. * 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.
  33649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33650. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33652. */
  33653. Mesh.CreatePolyhedron = function (name, options, scene) {
  33654. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33655. };
  33656. /**
  33657. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33658. * Please consider using the same method from the MeshBuilder class instead.
  33659. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33660. * 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`).
  33661. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33662. * 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.
  33663. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33664. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33666. */
  33667. Mesh.CreateIcoSphere = function (name, options, scene) {
  33668. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33669. };
  33670. /**
  33671. * Creates a decal mesh.
  33672. * Please consider using the same method from the MeshBuilder class instead.
  33673. * 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.
  33674. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33675. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33676. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33677. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33678. */
  33679. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33680. var options = {
  33681. position: position,
  33682. normal: normal,
  33683. size: size,
  33684. angle: angle
  33685. };
  33686. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33687. };
  33688. // Skeletons
  33689. /**
  33690. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33691. */
  33692. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33693. if (!this._sourcePositions) {
  33694. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33695. if (!source) {
  33696. return this._sourcePositions;
  33697. }
  33698. this._sourcePositions = new Float32Array(source);
  33699. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33700. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33701. }
  33702. }
  33703. return this._sourcePositions;
  33704. };
  33705. /**
  33706. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33707. */
  33708. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33709. if (!this._sourceNormals) {
  33710. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33711. if (!source) {
  33712. return this._sourceNormals;
  33713. }
  33714. this._sourceNormals = new Float32Array(source);
  33715. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33716. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33717. }
  33718. }
  33719. return this._sourceNormals;
  33720. };
  33721. /**
  33722. * Updates the vertex buffer by applying transformation from the bones.
  33723. * Returns the Mesh.
  33724. *
  33725. * @param {skeleton} skeleton to apply
  33726. */
  33727. Mesh.prototype.applySkeleton = function (skeleton) {
  33728. if (!this.geometry) {
  33729. return this;
  33730. }
  33731. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33732. return this;
  33733. }
  33734. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33735. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33736. return this;
  33737. }
  33738. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33739. return this;
  33740. }
  33741. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33742. return this;
  33743. }
  33744. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33745. return this;
  33746. }
  33747. if (!this._sourcePositions) {
  33748. var submeshes = this.subMeshes.slice();
  33749. this.setPositionsForCPUSkinning();
  33750. this.subMeshes = submeshes;
  33751. }
  33752. if (!this._sourceNormals) {
  33753. this.setNormalsForCPUSkinning();
  33754. }
  33755. // positionsData checks for not being Float32Array will only pass at most once
  33756. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33757. if (!positionsData) {
  33758. return this;
  33759. }
  33760. if (!(positionsData instanceof Float32Array)) {
  33761. positionsData = new Float32Array(positionsData);
  33762. }
  33763. // normalsData checks for not being Float32Array will only pass at most once
  33764. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33765. if (!normalsData) {
  33766. return this;
  33767. }
  33768. if (!(normalsData instanceof Float32Array)) {
  33769. normalsData = new Float32Array(normalsData);
  33770. }
  33771. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33772. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33773. if (!matricesWeightsData || !matricesIndicesData) {
  33774. return this;
  33775. }
  33776. var needExtras = this.numBoneInfluencers > 4;
  33777. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33778. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33779. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33780. var tempVector3 = BABYLON.Vector3.Zero();
  33781. var finalMatrix = new BABYLON.Matrix();
  33782. var tempMatrix = new BABYLON.Matrix();
  33783. var matWeightIdx = 0;
  33784. var inf;
  33785. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33786. var weight;
  33787. for (inf = 0; inf < 4; inf++) {
  33788. weight = matricesWeightsData[matWeightIdx + inf];
  33789. if (weight > 0) {
  33790. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33791. finalMatrix.addToSelf(tempMatrix);
  33792. }
  33793. }
  33794. if (needExtras) {
  33795. for (inf = 0; inf < 4; inf++) {
  33796. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33797. if (weight > 0) {
  33798. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33799. finalMatrix.addToSelf(tempMatrix);
  33800. }
  33801. }
  33802. }
  33803. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33804. tempVector3.toArray(positionsData, index);
  33805. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33806. tempVector3.toArray(normalsData, index);
  33807. finalMatrix.reset();
  33808. }
  33809. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33810. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33811. return this;
  33812. };
  33813. // Tools
  33814. /**
  33815. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33816. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33817. */
  33818. Mesh.MinMax = function (meshes) {
  33819. var minVector = null;
  33820. var maxVector = null;
  33821. meshes.forEach(function (mesh, index, array) {
  33822. var boundingInfo = mesh.getBoundingInfo();
  33823. var boundingBox = boundingInfo.boundingBox;
  33824. if (!minVector || !maxVector) {
  33825. minVector = boundingBox.minimumWorld;
  33826. maxVector = boundingBox.maximumWorld;
  33827. }
  33828. else {
  33829. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33830. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33831. }
  33832. });
  33833. if (!minVector || !maxVector) {
  33834. return {
  33835. min: BABYLON.Vector3.Zero(),
  33836. max: BABYLON.Vector3.Zero()
  33837. };
  33838. }
  33839. return {
  33840. min: minVector,
  33841. max: maxVector
  33842. };
  33843. };
  33844. /**
  33845. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33846. */
  33847. Mesh.Center = function (meshesOrMinMaxVector) {
  33848. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33849. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33850. };
  33851. /**
  33852. * Merge the array of meshes into a single mesh for performance reasons.
  33853. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33854. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33855. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33856. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33857. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33858. */
  33859. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33860. if (disposeSource === void 0) { disposeSource = true; }
  33861. var index;
  33862. if (!allow32BitsIndices) {
  33863. var totalVertices = 0;
  33864. // Counting vertices
  33865. for (index = 0; index < meshes.length; index++) {
  33866. if (meshes[index]) {
  33867. totalVertices += meshes[index].getTotalVertices();
  33868. if (totalVertices > 65536) {
  33869. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33870. return null;
  33871. }
  33872. }
  33873. }
  33874. }
  33875. // Merge
  33876. var vertexData = null;
  33877. var otherVertexData;
  33878. var indiceArray = new Array();
  33879. var source = null;
  33880. for (index = 0; index < meshes.length; index++) {
  33881. if (meshes[index]) {
  33882. meshes[index].computeWorldMatrix(true);
  33883. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33884. otherVertexData.transform(meshes[index].getWorldMatrix());
  33885. if (vertexData) {
  33886. vertexData.merge(otherVertexData);
  33887. }
  33888. else {
  33889. vertexData = otherVertexData;
  33890. source = meshes[index];
  33891. }
  33892. if (subdivideWithSubMeshes) {
  33893. indiceArray.push(meshes[index].getTotalIndices());
  33894. }
  33895. }
  33896. }
  33897. source = source;
  33898. if (!meshSubclass) {
  33899. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33900. }
  33901. vertexData.applyToMesh(meshSubclass);
  33902. // Setting properties
  33903. meshSubclass.material = source.material;
  33904. meshSubclass.checkCollisions = source.checkCollisions;
  33905. // Cleaning
  33906. if (disposeSource) {
  33907. for (index = 0; index < meshes.length; index++) {
  33908. if (meshes[index]) {
  33909. meshes[index].dispose();
  33910. }
  33911. }
  33912. }
  33913. // Subdivide
  33914. if (subdivideWithSubMeshes) {
  33915. //-- removal of global submesh
  33916. meshSubclass.releaseSubMeshes();
  33917. index = 0;
  33918. var offset = 0;
  33919. //-- apply subdivision according to index table
  33920. while (index < indiceArray.length) {
  33921. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33922. offset += indiceArray[index];
  33923. index++;
  33924. }
  33925. }
  33926. return meshSubclass;
  33927. };
  33928. // Consts
  33929. Mesh._FRONTSIDE = 0;
  33930. Mesh._BACKSIDE = 1;
  33931. Mesh._DOUBLESIDE = 2;
  33932. Mesh._DEFAULTSIDE = 0;
  33933. Mesh._NO_CAP = 0;
  33934. Mesh._CAP_START = 1;
  33935. Mesh._CAP_END = 2;
  33936. Mesh._CAP_ALL = 3;
  33937. return Mesh;
  33938. }(BABYLON.AbstractMesh));
  33939. BABYLON.Mesh = Mesh;
  33940. })(BABYLON || (BABYLON = {}));
  33941. //# sourceMappingURL=babylon.mesh.js.map
  33942. var BABYLON;
  33943. (function (BABYLON) {
  33944. var BaseSubMesh = /** @class */ (function () {
  33945. function BaseSubMesh() {
  33946. }
  33947. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33948. get: function () {
  33949. return this._materialEffect;
  33950. },
  33951. enumerable: true,
  33952. configurable: true
  33953. });
  33954. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33955. if (defines === void 0) { defines = null; }
  33956. if (this._materialEffect === effect) {
  33957. if (!effect) {
  33958. this._materialDefines = null;
  33959. }
  33960. return;
  33961. }
  33962. this._materialDefines = defines;
  33963. this._materialEffect = effect;
  33964. };
  33965. return BaseSubMesh;
  33966. }());
  33967. BABYLON.BaseSubMesh = BaseSubMesh;
  33968. var SubMesh = /** @class */ (function (_super) {
  33969. __extends(SubMesh, _super);
  33970. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33971. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33972. var _this = _super.call(this) || this;
  33973. _this.materialIndex = materialIndex;
  33974. _this.verticesStart = verticesStart;
  33975. _this.verticesCount = verticesCount;
  33976. _this.indexStart = indexStart;
  33977. _this.indexCount = indexCount;
  33978. _this._renderId = 0;
  33979. _this._mesh = mesh;
  33980. _this._renderingMesh = renderingMesh || mesh;
  33981. mesh.subMeshes.push(_this);
  33982. _this._trianglePlanes = [];
  33983. _this._id = mesh.subMeshes.length - 1;
  33984. if (createBoundingBox) {
  33985. _this.refreshBoundingInfo();
  33986. mesh.computeWorldMatrix(true);
  33987. }
  33988. return _this;
  33989. }
  33990. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33991. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33992. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33993. };
  33994. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33995. get: function () {
  33996. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33997. },
  33998. enumerable: true,
  33999. configurable: true
  34000. });
  34001. /**
  34002. * Returns the submesh BoudingInfo object.
  34003. */
  34004. SubMesh.prototype.getBoundingInfo = function () {
  34005. if (this.IsGlobal) {
  34006. return this._mesh.getBoundingInfo();
  34007. }
  34008. return this._boundingInfo;
  34009. };
  34010. /**
  34011. * Sets the submesh BoundingInfo.
  34012. * Return the SubMesh.
  34013. */
  34014. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34015. this._boundingInfo = boundingInfo;
  34016. return this;
  34017. };
  34018. /**
  34019. * Returns the mesh of the current submesh.
  34020. */
  34021. SubMesh.prototype.getMesh = function () {
  34022. return this._mesh;
  34023. };
  34024. /**
  34025. * Returns the rendering mesh of the submesh.
  34026. */
  34027. SubMesh.prototype.getRenderingMesh = function () {
  34028. return this._renderingMesh;
  34029. };
  34030. /**
  34031. * Returns the submesh material.
  34032. */
  34033. SubMesh.prototype.getMaterial = function () {
  34034. var rootMaterial = this._renderingMesh.material;
  34035. if (rootMaterial === null || rootMaterial === undefined) {
  34036. return this._mesh.getScene().defaultMaterial;
  34037. }
  34038. else if (rootMaterial.getSubMaterial) {
  34039. var multiMaterial = rootMaterial;
  34040. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34041. if (this._currentMaterial !== effectiveMaterial) {
  34042. this._currentMaterial = effectiveMaterial;
  34043. this._materialDefines = null;
  34044. }
  34045. return effectiveMaterial;
  34046. }
  34047. return rootMaterial;
  34048. };
  34049. // Methods
  34050. /**
  34051. * Sets a new updated BoundingInfo object to the submesh.
  34052. * Returns the SubMesh.
  34053. */
  34054. SubMesh.prototype.refreshBoundingInfo = function () {
  34055. this._lastColliderWorldVertices = null;
  34056. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34057. return this;
  34058. }
  34059. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34060. if (!data) {
  34061. this._boundingInfo = this._mesh.getBoundingInfo();
  34062. return this;
  34063. }
  34064. var indices = this._renderingMesh.getIndices();
  34065. var extend;
  34066. //is this the only submesh?
  34067. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34068. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34069. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34070. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34071. }
  34072. else {
  34073. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34074. }
  34075. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34076. return this;
  34077. };
  34078. SubMesh.prototype._checkCollision = function (collider) {
  34079. var boundingInfo = this.getBoundingInfo();
  34080. return boundingInfo._checkCollision(collider);
  34081. };
  34082. /**
  34083. * Updates the submesh BoundingInfo.
  34084. * Returns the Submesh.
  34085. */
  34086. SubMesh.prototype.updateBoundingInfo = function (world) {
  34087. var boundingInfo = this.getBoundingInfo();
  34088. if (!boundingInfo) {
  34089. this.refreshBoundingInfo();
  34090. boundingInfo = this.getBoundingInfo();
  34091. }
  34092. boundingInfo.update(world);
  34093. return this;
  34094. };
  34095. /**
  34096. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34097. * Boolean returned.
  34098. */
  34099. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34100. var boundingInfo = this.getBoundingInfo();
  34101. if (!boundingInfo) {
  34102. return false;
  34103. }
  34104. return boundingInfo.isInFrustum(frustumPlanes);
  34105. };
  34106. /**
  34107. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34108. * Boolean returned.
  34109. */
  34110. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34111. var boundingInfo = this.getBoundingInfo();
  34112. if (!boundingInfo) {
  34113. return false;
  34114. }
  34115. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34116. };
  34117. /**
  34118. * Renders the submesh.
  34119. * Returns it.
  34120. */
  34121. SubMesh.prototype.render = function (enableAlphaMode) {
  34122. this._renderingMesh.render(this, enableAlphaMode);
  34123. return this;
  34124. };
  34125. /**
  34126. * Returns a new Index Buffer.
  34127. * Type returned : WebGLBuffer.
  34128. */
  34129. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34130. if (!this._linesIndexBuffer) {
  34131. var linesIndices = [];
  34132. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34133. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34134. }
  34135. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34136. this.linesIndexCount = linesIndices.length;
  34137. }
  34138. return this._linesIndexBuffer;
  34139. };
  34140. /**
  34141. * True is the passed Ray intersects the submesh bounding box.
  34142. * Boolean returned.
  34143. */
  34144. SubMesh.prototype.canIntersects = function (ray) {
  34145. var boundingInfo = this.getBoundingInfo();
  34146. if (!boundingInfo) {
  34147. return false;
  34148. }
  34149. return ray.intersectsBox(boundingInfo.boundingBox);
  34150. };
  34151. /**
  34152. * Returns an object IntersectionInfo.
  34153. */
  34154. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34155. var intersectInfo = null;
  34156. var material = this.getMaterial();
  34157. if (!material) {
  34158. return null;
  34159. }
  34160. switch (material.fillMode) {
  34161. case BABYLON.Material.PointListDrawMode:
  34162. case BABYLON.Material.LineListDrawMode:
  34163. case BABYLON.Material.LineLoopDrawMode:
  34164. case BABYLON.Material.LineStripDrawMode:
  34165. case BABYLON.Material.TriangleFanDrawMode:
  34166. case BABYLON.Material.TriangleStripDrawMode:
  34167. return null;
  34168. }
  34169. // LineMesh first as it's also a Mesh...
  34170. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34171. var lineMesh = this._mesh;
  34172. // Line test
  34173. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34174. var p0 = positions[indices[index]];
  34175. var p1 = positions[indices[index + 1]];
  34176. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34177. if (length < 0) {
  34178. continue;
  34179. }
  34180. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34181. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34182. if (fastCheck) {
  34183. break;
  34184. }
  34185. }
  34186. }
  34187. }
  34188. else {
  34189. // Triangles test
  34190. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34191. var p0 = positions[indices[index]];
  34192. var p1 = positions[indices[index + 1]];
  34193. var p2 = positions[indices[index + 2]];
  34194. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34195. if (currentIntersectInfo) {
  34196. if (currentIntersectInfo.distance < 0) {
  34197. continue;
  34198. }
  34199. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34200. intersectInfo = currentIntersectInfo;
  34201. intersectInfo.faceId = index / 3;
  34202. if (fastCheck) {
  34203. break;
  34204. }
  34205. }
  34206. }
  34207. }
  34208. }
  34209. return intersectInfo;
  34210. };
  34211. SubMesh.prototype._rebuild = function () {
  34212. if (this._linesIndexBuffer) {
  34213. this._linesIndexBuffer = null;
  34214. }
  34215. };
  34216. // Clone
  34217. /**
  34218. * Creates a new Submesh from the passed Mesh.
  34219. */
  34220. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34221. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34222. if (!this.IsGlobal) {
  34223. var boundingInfo = this.getBoundingInfo();
  34224. if (!boundingInfo) {
  34225. return result;
  34226. }
  34227. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34228. }
  34229. return result;
  34230. };
  34231. // Dispose
  34232. /**
  34233. * Disposes the Submesh.
  34234. * Returns nothing.
  34235. */
  34236. SubMesh.prototype.dispose = function () {
  34237. if (this._linesIndexBuffer) {
  34238. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34239. this._linesIndexBuffer = null;
  34240. }
  34241. // Remove from mesh
  34242. var index = this._mesh.subMeshes.indexOf(this);
  34243. this._mesh.subMeshes.splice(index, 1);
  34244. };
  34245. // Statics
  34246. /**
  34247. * Creates a new Submesh from the passed parameters :
  34248. * - materialIndex (integer) : the index of the main mesh material.
  34249. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34250. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34251. * - mesh (Mesh) : the main mesh to create the submesh from.
  34252. * - renderingMesh (optional Mesh) : rendering mesh.
  34253. */
  34254. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34255. var minVertexIndex = Number.MAX_VALUE;
  34256. var maxVertexIndex = -Number.MAX_VALUE;
  34257. renderingMesh = (renderingMesh || mesh);
  34258. var indices = renderingMesh.getIndices();
  34259. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34260. var vertexIndex = indices[index];
  34261. if (vertexIndex < minVertexIndex)
  34262. minVertexIndex = vertexIndex;
  34263. if (vertexIndex > maxVertexIndex)
  34264. maxVertexIndex = vertexIndex;
  34265. }
  34266. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34267. };
  34268. return SubMesh;
  34269. }(BaseSubMesh));
  34270. BABYLON.SubMesh = SubMesh;
  34271. })(BABYLON || (BABYLON = {}));
  34272. //# sourceMappingURL=babylon.subMesh.js.map
  34273. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34274. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34275. s = arguments[i];
  34276. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34277. t[p] = s[p];
  34278. }
  34279. return t;
  34280. };
  34281. var BABYLON;
  34282. (function (BABYLON) {
  34283. /**
  34284. * Manages the defines for the Material
  34285. */
  34286. var MaterialDefines = /** @class */ (function () {
  34287. function MaterialDefines() {
  34288. this._isDirty = true;
  34289. /** @hidden */
  34290. this._areLightsDirty = true;
  34291. /** @hidden */
  34292. this._areAttributesDirty = true;
  34293. /** @hidden */
  34294. this._areTexturesDirty = true;
  34295. /** @hidden */
  34296. this._areFresnelDirty = true;
  34297. /** @hidden */
  34298. this._areMiscDirty = true;
  34299. /** @hidden */
  34300. this._areImageProcessingDirty = true;
  34301. /** @hidden */
  34302. this._normals = false;
  34303. /** @hidden */
  34304. this._uvs = false;
  34305. /** @hidden */
  34306. this._needNormals = false;
  34307. /** @hidden */
  34308. this._needUVs = false;
  34309. }
  34310. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34311. /**
  34312. * Specifies if the material needs to be re-calculated
  34313. */
  34314. get: function () {
  34315. return this._isDirty;
  34316. },
  34317. enumerable: true,
  34318. configurable: true
  34319. });
  34320. /**
  34321. * Marks the material to indicate that it has been re-calculated
  34322. */
  34323. MaterialDefines.prototype.markAsProcessed = function () {
  34324. this._isDirty = false;
  34325. this._areAttributesDirty = false;
  34326. this._areTexturesDirty = false;
  34327. this._areFresnelDirty = false;
  34328. this._areLightsDirty = false;
  34329. this._areMiscDirty = false;
  34330. this._areImageProcessingDirty = false;
  34331. };
  34332. /**
  34333. * Marks the material to indicate that it needs to be re-calculated
  34334. */
  34335. MaterialDefines.prototype.markAsUnprocessed = function () {
  34336. this._isDirty = true;
  34337. };
  34338. /**
  34339. * Marks the material to indicate all of its defines need to be re-calculated
  34340. */
  34341. MaterialDefines.prototype.markAllAsDirty = function () {
  34342. this._areTexturesDirty = true;
  34343. this._areAttributesDirty = true;
  34344. this._areLightsDirty = true;
  34345. this._areFresnelDirty = true;
  34346. this._areMiscDirty = true;
  34347. this._areImageProcessingDirty = true;
  34348. this._isDirty = true;
  34349. };
  34350. /**
  34351. * Marks the material to indicate that image processing needs to be re-calculated
  34352. */
  34353. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34354. this._areImageProcessingDirty = true;
  34355. this._isDirty = true;
  34356. };
  34357. /**
  34358. * Marks the material to indicate the lights need to be re-calculated
  34359. */
  34360. MaterialDefines.prototype.markAsLightDirty = function () {
  34361. this._areLightsDirty = true;
  34362. this._isDirty = true;
  34363. };
  34364. /**
  34365. * Marks the attribute state as changed
  34366. */
  34367. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34368. this._areAttributesDirty = true;
  34369. this._isDirty = true;
  34370. };
  34371. /**
  34372. * Marks the texture state as changed
  34373. */
  34374. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34375. this._areTexturesDirty = true;
  34376. this._isDirty = true;
  34377. };
  34378. /**
  34379. * Marks the fresnel state as changed
  34380. */
  34381. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34382. this._areFresnelDirty = true;
  34383. this._isDirty = true;
  34384. };
  34385. /**
  34386. * Marks the misc state as changed
  34387. */
  34388. MaterialDefines.prototype.markAsMiscDirty = function () {
  34389. this._areMiscDirty = true;
  34390. this._isDirty = true;
  34391. };
  34392. /**
  34393. * Rebuilds the material defines
  34394. */
  34395. MaterialDefines.prototype.rebuild = function () {
  34396. if (this._keys) {
  34397. delete this._keys;
  34398. }
  34399. this._keys = [];
  34400. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34401. var key = _a[_i];
  34402. if (key[0] === "_") {
  34403. continue;
  34404. }
  34405. this._keys.push(key);
  34406. }
  34407. };
  34408. /**
  34409. * Specifies if two material defines are equal
  34410. * @param other - A material define instance to compare to
  34411. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34412. */
  34413. MaterialDefines.prototype.isEqual = function (other) {
  34414. if (this._keys.length !== other._keys.length) {
  34415. return false;
  34416. }
  34417. for (var index = 0; index < this._keys.length; index++) {
  34418. var prop = this._keys[index];
  34419. if (this[prop] !== other[prop]) {
  34420. return false;
  34421. }
  34422. }
  34423. return true;
  34424. };
  34425. /**
  34426. * Clones this instance's defines to another instance
  34427. * @param other - material defines to clone values to
  34428. */
  34429. MaterialDefines.prototype.cloneTo = function (other) {
  34430. if (this._keys.length !== other._keys.length) {
  34431. other._keys = this._keys.slice(0);
  34432. }
  34433. for (var index = 0; index < this._keys.length; index++) {
  34434. var prop = this._keys[index];
  34435. other[prop] = this[prop];
  34436. }
  34437. };
  34438. /**
  34439. * Resets the material define values
  34440. */
  34441. MaterialDefines.prototype.reset = function () {
  34442. for (var index = 0; index < this._keys.length; index++) {
  34443. var prop = this._keys[index];
  34444. var type = typeof this[prop];
  34445. switch (type) {
  34446. case "number":
  34447. this[prop] = 0;
  34448. break;
  34449. case "string":
  34450. this[prop] = "";
  34451. break;
  34452. default:
  34453. this[prop] = false;
  34454. break;
  34455. }
  34456. }
  34457. };
  34458. /**
  34459. * Converts the material define values to a string
  34460. * @returns - String of material define information
  34461. */
  34462. MaterialDefines.prototype.toString = function () {
  34463. var result = "";
  34464. for (var index = 0; index < this._keys.length; index++) {
  34465. var prop = this._keys[index];
  34466. var value = this[prop];
  34467. var type = typeof value;
  34468. switch (type) {
  34469. case "number":
  34470. case "string":
  34471. result += "#define " + prop + " " + value + "\n";
  34472. break;
  34473. default:
  34474. if (value) {
  34475. result += "#define " + prop + "\n";
  34476. }
  34477. break;
  34478. }
  34479. }
  34480. return result;
  34481. };
  34482. return MaterialDefines;
  34483. }());
  34484. BABYLON.MaterialDefines = MaterialDefines;
  34485. /**
  34486. * Base class for the main features of a material in Babylon.js
  34487. */
  34488. var Material = /** @class */ (function () {
  34489. /**
  34490. * Creates a material instance
  34491. * @param name defines the name of the material
  34492. * @param scene defines the scene to reference
  34493. * @param doNotAdd specifies if the material should be added to the scene
  34494. */
  34495. function Material(name, scene, doNotAdd) {
  34496. /**
  34497. * Specifies if the ready state should be checked on each call
  34498. */
  34499. this.checkReadyOnEveryCall = false;
  34500. /**
  34501. * Specifies if the ready state should be checked once
  34502. */
  34503. this.checkReadyOnlyOnce = false;
  34504. /**
  34505. * The state of the material
  34506. */
  34507. this.state = "";
  34508. /**
  34509. * The alpha value of the material
  34510. */
  34511. this._alpha = 1.0;
  34512. /**
  34513. * Specifies if back face culling is enabled
  34514. */
  34515. this._backFaceCulling = true;
  34516. /**
  34517. * Specifies if the material should be serialized
  34518. */
  34519. this.doNotSerialize = false;
  34520. /**
  34521. * Specifies if the effect should be stored on sub meshes
  34522. */
  34523. this.storeEffectOnSubMeshes = false;
  34524. /**
  34525. * An event triggered when the material is disposed
  34526. */
  34527. this.onDisposeObservable = new BABYLON.Observable();
  34528. /**
  34529. * An event triggered when the material is bound
  34530. */
  34531. this.onBindObservable = new BABYLON.Observable();
  34532. /**
  34533. * An event triggered when the material is unbound
  34534. */
  34535. this.onUnBindObservable = new BABYLON.Observable();
  34536. /**
  34537. * Stores the value of the alpha mode
  34538. */
  34539. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34540. /**
  34541. * Stores the state of the need depth pre-pass value
  34542. */
  34543. this._needDepthPrePass = false;
  34544. /**
  34545. * Specifies if depth writing should be disabled
  34546. */
  34547. this.disableDepthWrite = false;
  34548. /**
  34549. * Specifies if depth writing should be forced
  34550. */
  34551. this.forceDepthWrite = false;
  34552. /**
  34553. * Specifies if there should be a separate pass for culling
  34554. */
  34555. this.separateCullingPass = false;
  34556. /**
  34557. * Stores the state specifing if fog should be enabled
  34558. */
  34559. this._fogEnabled = true;
  34560. /**
  34561. * Stores the size of points
  34562. */
  34563. this.pointSize = 1.0;
  34564. /**
  34565. * Stores the z offset value
  34566. */
  34567. this.zOffset = 0;
  34568. /**
  34569. * Specifies if the material was previously ready
  34570. */
  34571. this._wasPreviouslyReady = false;
  34572. /**
  34573. * Stores the fill mode state
  34574. */
  34575. this._fillMode = Material.TriangleFillMode;
  34576. this.name = name;
  34577. this.id = name || BABYLON.Tools.RandomId();
  34578. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34579. this.uniqueId = this._scene.getUniqueId();
  34580. if (this._scene.useRightHandedSystem) {
  34581. this.sideOrientation = Material.ClockWiseSideOrientation;
  34582. }
  34583. else {
  34584. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34585. }
  34586. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34587. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34588. if (!doNotAdd) {
  34589. this._scene.materials.push(this);
  34590. }
  34591. }
  34592. Object.defineProperty(Material, "TriangleFillMode", {
  34593. /**
  34594. * Returns the triangle fill mode
  34595. */
  34596. get: function () {
  34597. return Material._TriangleFillMode;
  34598. },
  34599. enumerable: true,
  34600. configurable: true
  34601. });
  34602. Object.defineProperty(Material, "WireFrameFillMode", {
  34603. /**
  34604. * Returns the wireframe mode
  34605. */
  34606. get: function () {
  34607. return Material._WireFrameFillMode;
  34608. },
  34609. enumerable: true,
  34610. configurable: true
  34611. });
  34612. Object.defineProperty(Material, "PointFillMode", {
  34613. /**
  34614. * Returns the point fill mode
  34615. */
  34616. get: function () {
  34617. return Material._PointFillMode;
  34618. },
  34619. enumerable: true,
  34620. configurable: true
  34621. });
  34622. Object.defineProperty(Material, "PointListDrawMode", {
  34623. /**
  34624. * Returns the point list draw mode
  34625. */
  34626. get: function () {
  34627. return Material._PointListDrawMode;
  34628. },
  34629. enumerable: true,
  34630. configurable: true
  34631. });
  34632. Object.defineProperty(Material, "LineListDrawMode", {
  34633. /**
  34634. * Returns the line list draw mode
  34635. */
  34636. get: function () {
  34637. return Material._LineListDrawMode;
  34638. },
  34639. enumerable: true,
  34640. configurable: true
  34641. });
  34642. Object.defineProperty(Material, "LineLoopDrawMode", {
  34643. /**
  34644. * Returns the line loop draw mode
  34645. */
  34646. get: function () {
  34647. return Material._LineLoopDrawMode;
  34648. },
  34649. enumerable: true,
  34650. configurable: true
  34651. });
  34652. Object.defineProperty(Material, "LineStripDrawMode", {
  34653. /**
  34654. * Returns the line strip draw mode
  34655. */
  34656. get: function () {
  34657. return Material._LineStripDrawMode;
  34658. },
  34659. enumerable: true,
  34660. configurable: true
  34661. });
  34662. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34663. /**
  34664. * Returns the triangle strip draw mode
  34665. */
  34666. get: function () {
  34667. return Material._TriangleStripDrawMode;
  34668. },
  34669. enumerable: true,
  34670. configurable: true
  34671. });
  34672. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34673. /**
  34674. * Returns the triangle fan draw mode
  34675. */
  34676. get: function () {
  34677. return Material._TriangleFanDrawMode;
  34678. },
  34679. enumerable: true,
  34680. configurable: true
  34681. });
  34682. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34683. /**
  34684. * Returns the clock-wise side orientation
  34685. */
  34686. get: function () {
  34687. return Material._ClockWiseSideOrientation;
  34688. },
  34689. enumerable: true,
  34690. configurable: true
  34691. });
  34692. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34693. /**
  34694. * Returns the counter clock-wise side orientation
  34695. */
  34696. get: function () {
  34697. return Material._CounterClockWiseSideOrientation;
  34698. },
  34699. enumerable: true,
  34700. configurable: true
  34701. });
  34702. Object.defineProperty(Material, "TextureDirtyFlag", {
  34703. /**
  34704. * Returns the dirty texture flag value
  34705. */
  34706. get: function () {
  34707. return Material._TextureDirtyFlag;
  34708. },
  34709. enumerable: true,
  34710. configurable: true
  34711. });
  34712. Object.defineProperty(Material, "LightDirtyFlag", {
  34713. /**
  34714. * Returns the dirty light flag value
  34715. */
  34716. get: function () {
  34717. return Material._LightDirtyFlag;
  34718. },
  34719. enumerable: true,
  34720. configurable: true
  34721. });
  34722. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34723. /**
  34724. * Returns the dirty fresnel flag value
  34725. */
  34726. get: function () {
  34727. return Material._FresnelDirtyFlag;
  34728. },
  34729. enumerable: true,
  34730. configurable: true
  34731. });
  34732. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34733. /**
  34734. * Returns the dirty attributes flag value
  34735. */
  34736. get: function () {
  34737. return Material._AttributesDirtyFlag;
  34738. },
  34739. enumerable: true,
  34740. configurable: true
  34741. });
  34742. Object.defineProperty(Material, "MiscDirtyFlag", {
  34743. /**
  34744. * Returns the dirty misc flag value
  34745. */
  34746. get: function () {
  34747. return Material._MiscDirtyFlag;
  34748. },
  34749. enumerable: true,
  34750. configurable: true
  34751. });
  34752. Object.defineProperty(Material.prototype, "alpha", {
  34753. /**
  34754. * Gets the alpha value of the material
  34755. */
  34756. get: function () {
  34757. return this._alpha;
  34758. },
  34759. /**
  34760. * Sets the alpha value of the material
  34761. */
  34762. set: function (value) {
  34763. if (this._alpha === value) {
  34764. return;
  34765. }
  34766. this._alpha = value;
  34767. this.markAsDirty(Material.MiscDirtyFlag);
  34768. },
  34769. enumerable: true,
  34770. configurable: true
  34771. });
  34772. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34773. /**
  34774. * Gets the back-face culling state
  34775. */
  34776. get: function () {
  34777. return this._backFaceCulling;
  34778. },
  34779. /**
  34780. * Sets the back-face culling state
  34781. */
  34782. set: function (value) {
  34783. if (this._backFaceCulling === value) {
  34784. return;
  34785. }
  34786. this._backFaceCulling = value;
  34787. this.markAsDirty(Material.TextureDirtyFlag);
  34788. },
  34789. enumerable: true,
  34790. configurable: true
  34791. });
  34792. Object.defineProperty(Material.prototype, "onDispose", {
  34793. /**
  34794. * Called during a dispose event
  34795. */
  34796. set: function (callback) {
  34797. if (this._onDisposeObserver) {
  34798. this.onDisposeObservable.remove(this._onDisposeObserver);
  34799. }
  34800. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34801. },
  34802. enumerable: true,
  34803. configurable: true
  34804. });
  34805. Object.defineProperty(Material.prototype, "onBind", {
  34806. /**
  34807. * Called during a bind event
  34808. */
  34809. set: function (callback) {
  34810. if (this._onBindObserver) {
  34811. this.onBindObservable.remove(this._onBindObserver);
  34812. }
  34813. this._onBindObserver = this.onBindObservable.add(callback);
  34814. },
  34815. enumerable: true,
  34816. configurable: true
  34817. });
  34818. Object.defineProperty(Material.prototype, "alphaMode", {
  34819. /**
  34820. * Gets the value of the alpha mode
  34821. */
  34822. get: function () {
  34823. return this._alphaMode;
  34824. },
  34825. /**
  34826. * Sets the value of the alpha mode.
  34827. *
  34828. * | Value | Type | Description |
  34829. * | --- | --- | --- |
  34830. * | 0 | ALPHA_DISABLE | |
  34831. * | 1 | ALPHA_ADD | |
  34832. * | 2 | ALPHA_COMBINE | |
  34833. * | 3 | ALPHA_SUBTRACT | |
  34834. * | 4 | ALPHA_MULTIPLY | |
  34835. * | 5 | ALPHA_MAXIMIZED | |
  34836. * | 6 | ALPHA_ONEONE | |
  34837. * | 7 | ALPHA_PREMULTIPLIED | |
  34838. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34839. * | 9 | ALPHA_INTERPOLATE | |
  34840. * | 10 | ALPHA_SCREENMODE | |
  34841. *
  34842. */
  34843. set: function (value) {
  34844. if (this._alphaMode === value) {
  34845. return;
  34846. }
  34847. this._alphaMode = value;
  34848. this.markAsDirty(Material.TextureDirtyFlag);
  34849. },
  34850. enumerable: true,
  34851. configurable: true
  34852. });
  34853. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34854. /**
  34855. * Gets the depth pre-pass value
  34856. */
  34857. get: function () {
  34858. return this._needDepthPrePass;
  34859. },
  34860. /**
  34861. * Sets the need depth pre-pass value
  34862. */
  34863. set: function (value) {
  34864. if (this._needDepthPrePass === value) {
  34865. return;
  34866. }
  34867. this._needDepthPrePass = value;
  34868. if (this._needDepthPrePass) {
  34869. this.checkReadyOnEveryCall = true;
  34870. }
  34871. },
  34872. enumerable: true,
  34873. configurable: true
  34874. });
  34875. Object.defineProperty(Material.prototype, "fogEnabled", {
  34876. /**
  34877. * Gets the value of the fog enabled state
  34878. */
  34879. get: function () {
  34880. return this._fogEnabled;
  34881. },
  34882. /**
  34883. * Sets the state for enabling fog
  34884. */
  34885. set: function (value) {
  34886. if (this._fogEnabled === value) {
  34887. return;
  34888. }
  34889. this._fogEnabled = value;
  34890. this.markAsDirty(Material.MiscDirtyFlag);
  34891. },
  34892. enumerable: true,
  34893. configurable: true
  34894. });
  34895. Object.defineProperty(Material.prototype, "wireframe", {
  34896. /**
  34897. * Gets a value specifying if wireframe mode is enabled
  34898. */
  34899. get: function () {
  34900. switch (this._fillMode) {
  34901. case Material.WireFrameFillMode:
  34902. case Material.LineListDrawMode:
  34903. case Material.LineLoopDrawMode:
  34904. case Material.LineStripDrawMode:
  34905. return true;
  34906. }
  34907. return this._scene.forceWireframe;
  34908. },
  34909. /**
  34910. * Sets the state of wireframe mode
  34911. */
  34912. set: function (value) {
  34913. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34914. },
  34915. enumerable: true,
  34916. configurable: true
  34917. });
  34918. Object.defineProperty(Material.prototype, "pointsCloud", {
  34919. /**
  34920. * Gets the value specifying if point clouds are enabled
  34921. */
  34922. get: function () {
  34923. switch (this._fillMode) {
  34924. case Material.PointFillMode:
  34925. case Material.PointListDrawMode:
  34926. return true;
  34927. }
  34928. return this._scene.forcePointsCloud;
  34929. },
  34930. /**
  34931. * Sets the state of point cloud mode
  34932. */
  34933. set: function (value) {
  34934. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34935. },
  34936. enumerable: true,
  34937. configurable: true
  34938. });
  34939. Object.defineProperty(Material.prototype, "fillMode", {
  34940. /**
  34941. * Gets the material fill mode
  34942. */
  34943. get: function () {
  34944. return this._fillMode;
  34945. },
  34946. /**
  34947. * Sets the material fill mode
  34948. */
  34949. set: function (value) {
  34950. if (this._fillMode === value) {
  34951. return;
  34952. }
  34953. this._fillMode = value;
  34954. this.markAsDirty(Material.MiscDirtyFlag);
  34955. },
  34956. enumerable: true,
  34957. configurable: true
  34958. });
  34959. /**
  34960. * Returns a string representation of the current material
  34961. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34962. * @returns a string with material information
  34963. */
  34964. Material.prototype.toString = function (fullDetails) {
  34965. var ret = "Name: " + this.name;
  34966. if (fullDetails) {
  34967. }
  34968. return ret;
  34969. };
  34970. /**
  34971. * Gets the class name of the material
  34972. * @returns a string with the class name of the material
  34973. */
  34974. Material.prototype.getClassName = function () {
  34975. return "Material";
  34976. };
  34977. Object.defineProperty(Material.prototype, "isFrozen", {
  34978. /**
  34979. * Specifies if updates for the material been locked
  34980. */
  34981. get: function () {
  34982. return this.checkReadyOnlyOnce;
  34983. },
  34984. enumerable: true,
  34985. configurable: true
  34986. });
  34987. /**
  34988. * Locks updates for the material
  34989. */
  34990. Material.prototype.freeze = function () {
  34991. this.checkReadyOnlyOnce = true;
  34992. };
  34993. /**
  34994. * Unlocks updates for the material
  34995. */
  34996. Material.prototype.unfreeze = function () {
  34997. this.checkReadyOnlyOnce = false;
  34998. };
  34999. /**
  35000. * Specifies if the material is ready to be used
  35001. * @param mesh defines the mesh to check
  35002. * @param useInstances specifies if instances should be used
  35003. * @returns a boolean indicating if the material is ready to be used
  35004. */
  35005. Material.prototype.isReady = function (mesh, useInstances) {
  35006. return true;
  35007. };
  35008. /**
  35009. * Specifies that the submesh is ready to be used
  35010. * @param mesh defines the mesh to check
  35011. * @param subMesh defines which submesh to check
  35012. * @param useInstances specifies that instances should be used
  35013. * @returns a boolean indicating that the submesh is ready or not
  35014. */
  35015. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35016. return false;
  35017. };
  35018. /**
  35019. * Returns the material effect
  35020. * @returns the effect associated with the material
  35021. */
  35022. Material.prototype.getEffect = function () {
  35023. return this._effect;
  35024. };
  35025. /**
  35026. * Returns the current scene
  35027. * @returns a Scene
  35028. */
  35029. Material.prototype.getScene = function () {
  35030. return this._scene;
  35031. };
  35032. /**
  35033. * Specifies if the material will require alpha blending
  35034. * @returns a boolean specifying if alpha blending is needed
  35035. */
  35036. Material.prototype.needAlphaBlending = function () {
  35037. return (this.alpha < 1.0);
  35038. };
  35039. /**
  35040. * Specifies if the mesh will require alpha blending
  35041. * @param mesh defines the mesh to check
  35042. * @returns a boolean specifying if alpha blending is needed for the mesh
  35043. */
  35044. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35045. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35046. };
  35047. /**
  35048. * Specifies if this material should be rendered in alpha test mode
  35049. * @returns a boolean specifying if an alpha test is needed.
  35050. */
  35051. Material.prototype.needAlphaTesting = function () {
  35052. return false;
  35053. };
  35054. /**
  35055. * Gets the texture used for the alpha test
  35056. * @returns the texture to use for alpha testing
  35057. */
  35058. Material.prototype.getAlphaTestTexture = function () {
  35059. return null;
  35060. };
  35061. /**
  35062. * Marks the material to indicate that it needs to be re-calculated
  35063. */
  35064. Material.prototype.markDirty = function () {
  35065. this._wasPreviouslyReady = false;
  35066. };
  35067. /** @hidden */
  35068. Material.prototype._preBind = function (effect, overrideOrientation) {
  35069. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35070. var engine = this._scene.getEngine();
  35071. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35072. var reverse = orientation === Material.ClockWiseSideOrientation;
  35073. engine.enableEffect(effect ? effect : this._effect);
  35074. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35075. return reverse;
  35076. };
  35077. /**
  35078. * Binds the material to the mesh
  35079. * @param world defines the world transformation matrix
  35080. * @param mesh defines the mesh to bind the material to
  35081. */
  35082. Material.prototype.bind = function (world, mesh) {
  35083. };
  35084. /**
  35085. * Binds the submesh to the material
  35086. * @param world defines the world transformation matrix
  35087. * @param mesh defines the mesh containing the submesh
  35088. * @param subMesh defines the submesh to bind the material to
  35089. */
  35090. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35091. };
  35092. /**
  35093. * Binds the world matrix to the material
  35094. * @param world defines the world transformation matrix
  35095. */
  35096. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35097. };
  35098. /**
  35099. * Binds the scene's uniform buffer to the effect.
  35100. * @param effect defines the effect to bind to the scene uniform buffer
  35101. * @param sceneUbo defines the uniform buffer storing scene data
  35102. */
  35103. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35104. sceneUbo.bindToEffect(effect, "Scene");
  35105. };
  35106. /**
  35107. * Binds the view matrix to the effect
  35108. * @param effect defines the effect to bind the view matrix to
  35109. */
  35110. Material.prototype.bindView = function (effect) {
  35111. if (!this._useUBO) {
  35112. effect.setMatrix("view", this.getScene().getViewMatrix());
  35113. }
  35114. else {
  35115. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35116. }
  35117. };
  35118. /**
  35119. * Binds the view projection matrix to the effect
  35120. * @param effect defines the effect to bind the view projection matrix to
  35121. */
  35122. Material.prototype.bindViewProjection = function (effect) {
  35123. if (!this._useUBO) {
  35124. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35125. }
  35126. else {
  35127. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35128. }
  35129. };
  35130. /**
  35131. * Specifies if material alpha testing should be turned on for the mesh
  35132. * @param mesh defines the mesh to check
  35133. */
  35134. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35135. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35136. };
  35137. /**
  35138. * Processes to execute after binding the material to a mesh
  35139. * @param mesh defines the rendered mesh
  35140. */
  35141. Material.prototype._afterBind = function (mesh) {
  35142. this._scene._cachedMaterial = this;
  35143. if (mesh) {
  35144. this._scene._cachedVisibility = mesh.visibility;
  35145. }
  35146. else {
  35147. this._scene._cachedVisibility = 1;
  35148. }
  35149. if (mesh) {
  35150. this.onBindObservable.notifyObservers(mesh);
  35151. }
  35152. if (this.disableDepthWrite) {
  35153. var engine = this._scene.getEngine();
  35154. this._cachedDepthWriteState = engine.getDepthWrite();
  35155. engine.setDepthWrite(false);
  35156. }
  35157. };
  35158. /**
  35159. * Unbinds the material from the mesh
  35160. */
  35161. Material.prototype.unbind = function () {
  35162. this.onUnBindObservable.notifyObservers(this);
  35163. if (this.disableDepthWrite) {
  35164. var engine = this._scene.getEngine();
  35165. engine.setDepthWrite(this._cachedDepthWriteState);
  35166. }
  35167. };
  35168. /**
  35169. * Gets the active textures from the material
  35170. * @returns an array of textures
  35171. */
  35172. Material.prototype.getActiveTextures = function () {
  35173. return [];
  35174. };
  35175. /**
  35176. * Specifies if the material uses a texture
  35177. * @param texture defines the texture to check against the material
  35178. * @returns a boolean specifying if the material uses the texture
  35179. */
  35180. Material.prototype.hasTexture = function (texture) {
  35181. return false;
  35182. };
  35183. /**
  35184. * Makes a duplicate of the material, and gives it a new name
  35185. * @param name defines the new name for the duplicated material
  35186. * @returns the cloned material
  35187. */
  35188. Material.prototype.clone = function (name) {
  35189. return null;
  35190. };
  35191. /**
  35192. * Gets the meshes bound to the material
  35193. * @returns an array of meshes bound to the material
  35194. */
  35195. Material.prototype.getBindedMeshes = function () {
  35196. var result = new Array();
  35197. for (var index = 0; index < this._scene.meshes.length; index++) {
  35198. var mesh = this._scene.meshes[index];
  35199. if (mesh.material === this) {
  35200. result.push(mesh);
  35201. }
  35202. }
  35203. return result;
  35204. };
  35205. /**
  35206. * Force shader compilation
  35207. * @param mesh defines the mesh associated with this material
  35208. * @param onCompiled defines a function to execute once the material is compiled
  35209. * @param options defines the options to configure the compilation
  35210. */
  35211. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35212. var _this = this;
  35213. var localOptions = __assign({ clipPlane: false }, options);
  35214. var subMesh = new BABYLON.BaseSubMesh();
  35215. var scene = this.getScene();
  35216. var checkReady = function () {
  35217. if (!_this._scene || !_this._scene.getEngine()) {
  35218. return;
  35219. }
  35220. if (subMesh._materialDefines) {
  35221. subMesh._materialDefines._renderId = -1;
  35222. }
  35223. var clipPlaneState = scene.clipPlane;
  35224. if (localOptions.clipPlane) {
  35225. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35226. }
  35227. if (_this.storeEffectOnSubMeshes) {
  35228. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35229. if (onCompiled) {
  35230. onCompiled(_this);
  35231. }
  35232. }
  35233. else {
  35234. setTimeout(checkReady, 16);
  35235. }
  35236. }
  35237. else {
  35238. if (_this.isReady(mesh)) {
  35239. if (onCompiled) {
  35240. onCompiled(_this);
  35241. }
  35242. }
  35243. else {
  35244. setTimeout(checkReady, 16);
  35245. }
  35246. }
  35247. if (localOptions.clipPlane) {
  35248. scene.clipPlane = clipPlaneState;
  35249. }
  35250. };
  35251. checkReady();
  35252. };
  35253. /**
  35254. * Force shader compilation
  35255. * @param mesh defines the mesh that will use this material
  35256. * @param options defines additional options for compiling the shaders
  35257. * @returns a promise that resolves when the compilation completes
  35258. */
  35259. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35260. var _this = this;
  35261. return new Promise(function (resolve) {
  35262. _this.forceCompilation(mesh, function () {
  35263. resolve();
  35264. }, options);
  35265. });
  35266. };
  35267. /**
  35268. * Marks a define in the material to indicate that it needs to be re-computed
  35269. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35270. */
  35271. Material.prototype.markAsDirty = function (flag) {
  35272. if (flag & Material.TextureDirtyFlag) {
  35273. this._markAllSubMeshesAsTexturesDirty();
  35274. }
  35275. if (flag & Material.LightDirtyFlag) {
  35276. this._markAllSubMeshesAsLightsDirty();
  35277. }
  35278. if (flag & Material.FresnelDirtyFlag) {
  35279. this._markAllSubMeshesAsFresnelDirty();
  35280. }
  35281. if (flag & Material.AttributesDirtyFlag) {
  35282. this._markAllSubMeshesAsAttributesDirty();
  35283. }
  35284. if (flag & Material.MiscDirtyFlag) {
  35285. this._markAllSubMeshesAsMiscDirty();
  35286. }
  35287. this.getScene().resetCachedMaterial();
  35288. };
  35289. /**
  35290. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35291. * @param func defines a function which checks material defines against the submeshes
  35292. */
  35293. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35294. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35295. var mesh = _a[_i];
  35296. if (!mesh.subMeshes) {
  35297. continue;
  35298. }
  35299. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35300. var subMesh = _c[_b];
  35301. if (subMesh.getMaterial() !== this) {
  35302. continue;
  35303. }
  35304. if (!subMesh._materialDefines) {
  35305. continue;
  35306. }
  35307. func(subMesh._materialDefines);
  35308. }
  35309. }
  35310. };
  35311. /**
  35312. * Indicates that image processing needs to be re-calculated for all submeshes
  35313. */
  35314. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35315. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35316. };
  35317. /**
  35318. * Indicates that textures need to be re-calculated for all submeshes
  35319. */
  35320. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35321. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35322. };
  35323. /**
  35324. * Indicates that fresnel needs to be re-calculated for all submeshes
  35325. */
  35326. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35327. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35328. };
  35329. /**
  35330. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35331. */
  35332. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35333. this._markAllSubMeshesAsDirty(function (defines) {
  35334. defines.markAsFresnelDirty();
  35335. defines.markAsMiscDirty();
  35336. });
  35337. };
  35338. /**
  35339. * Indicates that lights need to be re-calculated for all submeshes
  35340. */
  35341. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35342. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35343. };
  35344. /**
  35345. * Indicates that attributes need to be re-calculated for all submeshes
  35346. */
  35347. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35348. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35349. };
  35350. /**
  35351. * Indicates that misc needs to be re-calculated for all submeshes
  35352. */
  35353. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35354. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35355. };
  35356. /**
  35357. * Indicates that textures and misc need to be re-calculated for all submeshes
  35358. */
  35359. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35360. this._markAllSubMeshesAsDirty(function (defines) {
  35361. defines.markAsTexturesDirty();
  35362. defines.markAsMiscDirty();
  35363. });
  35364. };
  35365. /**
  35366. * Disposes the material
  35367. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35368. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35369. */
  35370. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35371. // Animations
  35372. this.getScene().stopAnimation(this);
  35373. this.getScene().freeProcessedMaterials();
  35374. // Remove from scene
  35375. var index = this._scene.materials.indexOf(this);
  35376. if (index >= 0) {
  35377. this._scene.materials.splice(index, 1);
  35378. }
  35379. // Remove from meshes
  35380. for (index = 0; index < this._scene.meshes.length; index++) {
  35381. var mesh = this._scene.meshes[index];
  35382. if (mesh.material === this) {
  35383. mesh.material = null;
  35384. if (mesh.geometry) {
  35385. var geometry = (mesh.geometry);
  35386. if (this.storeEffectOnSubMeshes) {
  35387. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35388. var subMesh = _a[_i];
  35389. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35390. if (forceDisposeEffect && subMesh._materialEffect) {
  35391. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35392. }
  35393. }
  35394. }
  35395. else {
  35396. geometry._releaseVertexArrayObject(this._effect);
  35397. }
  35398. }
  35399. }
  35400. }
  35401. this._uniformBuffer.dispose();
  35402. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35403. if (forceDisposeEffect && this._effect) {
  35404. if (!this.storeEffectOnSubMeshes) {
  35405. this._scene.getEngine()._releaseEffect(this._effect);
  35406. }
  35407. this._effect = null;
  35408. }
  35409. // Callback
  35410. this.onDisposeObservable.notifyObservers(this);
  35411. this.onDisposeObservable.clear();
  35412. this.onBindObservable.clear();
  35413. this.onUnBindObservable.clear();
  35414. };
  35415. /**
  35416. * Serializes this material
  35417. * @returns the serialized material object
  35418. */
  35419. Material.prototype.serialize = function () {
  35420. return BABYLON.SerializationHelper.Serialize(this);
  35421. };
  35422. /**
  35423. * Creates a MultiMaterial from parsed MultiMaterial data.
  35424. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35425. * @param scene defines the hosting scene
  35426. * @returns a new MultiMaterial
  35427. */
  35428. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35429. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35430. multiMaterial.id = parsedMultiMaterial.id;
  35431. if (BABYLON.Tags) {
  35432. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35433. }
  35434. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35435. var subMatId = parsedMultiMaterial.materials[matIndex];
  35436. if (subMatId) {
  35437. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35438. }
  35439. else {
  35440. multiMaterial.subMaterials.push(null);
  35441. }
  35442. }
  35443. return multiMaterial;
  35444. };
  35445. /**
  35446. * Creates a material from parsed material data
  35447. * @param parsedMaterial defines parsed material data
  35448. * @param scene defines the hosting scene
  35449. * @param rootUrl defines the root URL to use to load textures
  35450. * @returns a new material
  35451. */
  35452. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35453. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35454. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35455. }
  35456. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35457. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35458. if (!BABYLON.LegacyPBRMaterial) {
  35459. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35460. return;
  35461. }
  35462. }
  35463. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35464. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35465. };
  35466. // Triangle views
  35467. Material._TriangleFillMode = 0;
  35468. Material._WireFrameFillMode = 1;
  35469. Material._PointFillMode = 2;
  35470. // Draw modes
  35471. Material._PointListDrawMode = 3;
  35472. Material._LineListDrawMode = 4;
  35473. Material._LineLoopDrawMode = 5;
  35474. Material._LineStripDrawMode = 6;
  35475. Material._TriangleStripDrawMode = 7;
  35476. Material._TriangleFanDrawMode = 8;
  35477. /**
  35478. * Stores the clock-wise side orientation
  35479. */
  35480. Material._ClockWiseSideOrientation = 0;
  35481. /**
  35482. * Stores the counter clock-wise side orientation
  35483. */
  35484. Material._CounterClockWiseSideOrientation = 1;
  35485. /**
  35486. * The dirty texture flag value
  35487. */
  35488. Material._TextureDirtyFlag = 1;
  35489. /**
  35490. * The dirty light flag value
  35491. */
  35492. Material._LightDirtyFlag = 2;
  35493. /**
  35494. * The dirty fresnel flag value
  35495. */
  35496. Material._FresnelDirtyFlag = 4;
  35497. /**
  35498. * The dirty attribute flag value
  35499. */
  35500. Material._AttributesDirtyFlag = 8;
  35501. /**
  35502. * The dirty misc flag value
  35503. */
  35504. Material._MiscDirtyFlag = 16;
  35505. __decorate([
  35506. BABYLON.serialize()
  35507. ], Material.prototype, "id", void 0);
  35508. __decorate([
  35509. BABYLON.serialize()
  35510. ], Material.prototype, "uniqueId", void 0);
  35511. __decorate([
  35512. BABYLON.serialize()
  35513. ], Material.prototype, "name", void 0);
  35514. __decorate([
  35515. BABYLON.serialize()
  35516. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35517. __decorate([
  35518. BABYLON.serialize()
  35519. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35520. __decorate([
  35521. BABYLON.serialize()
  35522. ], Material.prototype, "state", void 0);
  35523. __decorate([
  35524. BABYLON.serialize("alpha")
  35525. ], Material.prototype, "_alpha", void 0);
  35526. __decorate([
  35527. BABYLON.serialize("backFaceCulling")
  35528. ], Material.prototype, "_backFaceCulling", void 0);
  35529. __decorate([
  35530. BABYLON.serialize()
  35531. ], Material.prototype, "sideOrientation", void 0);
  35532. __decorate([
  35533. BABYLON.serialize("alphaMode")
  35534. ], Material.prototype, "_alphaMode", void 0);
  35535. __decorate([
  35536. BABYLON.serialize()
  35537. ], Material.prototype, "_needDepthPrePass", void 0);
  35538. __decorate([
  35539. BABYLON.serialize()
  35540. ], Material.prototype, "disableDepthWrite", void 0);
  35541. __decorate([
  35542. BABYLON.serialize()
  35543. ], Material.prototype, "forceDepthWrite", void 0);
  35544. __decorate([
  35545. BABYLON.serialize()
  35546. ], Material.prototype, "separateCullingPass", void 0);
  35547. __decorate([
  35548. BABYLON.serialize("fogEnabled")
  35549. ], Material.prototype, "_fogEnabled", void 0);
  35550. __decorate([
  35551. BABYLON.serialize()
  35552. ], Material.prototype, "pointSize", void 0);
  35553. __decorate([
  35554. BABYLON.serialize()
  35555. ], Material.prototype, "zOffset", void 0);
  35556. __decorate([
  35557. BABYLON.serialize()
  35558. ], Material.prototype, "wireframe", null);
  35559. __decorate([
  35560. BABYLON.serialize()
  35561. ], Material.prototype, "pointsCloud", null);
  35562. __decorate([
  35563. BABYLON.serialize()
  35564. ], Material.prototype, "fillMode", null);
  35565. return Material;
  35566. }());
  35567. BABYLON.Material = Material;
  35568. })(BABYLON || (BABYLON = {}));
  35569. //# sourceMappingURL=babylon.material.js.map
  35570. var BABYLON;
  35571. (function (BABYLON) {
  35572. var UniformBuffer = /** @class */ (function () {
  35573. /**
  35574. * Uniform buffer objects.
  35575. *
  35576. * Handles blocks of uniform on the GPU.
  35577. *
  35578. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35579. *
  35580. * For more information, please refer to :
  35581. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35582. */
  35583. function UniformBuffer(engine, data, dynamic) {
  35584. this._engine = engine;
  35585. this._noUBO = !engine.supportsUniformBuffers;
  35586. this._dynamic = dynamic;
  35587. this._data = data || [];
  35588. this._uniformLocations = {};
  35589. this._uniformSizes = {};
  35590. this._uniformLocationPointer = 0;
  35591. this._needSync = false;
  35592. if (this._noUBO) {
  35593. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35594. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35595. this.updateFloat = this._updateFloatForEffect;
  35596. this.updateFloat2 = this._updateFloat2ForEffect;
  35597. this.updateFloat3 = this._updateFloat3ForEffect;
  35598. this.updateFloat4 = this._updateFloat4ForEffect;
  35599. this.updateMatrix = this._updateMatrixForEffect;
  35600. this.updateVector3 = this._updateVector3ForEffect;
  35601. this.updateVector4 = this._updateVector4ForEffect;
  35602. this.updateColor3 = this._updateColor3ForEffect;
  35603. this.updateColor4 = this._updateColor4ForEffect;
  35604. }
  35605. else {
  35606. this._engine._uniformBuffers.push(this);
  35607. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35608. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35609. this.updateFloat = this._updateFloatForUniform;
  35610. this.updateFloat2 = this._updateFloat2ForUniform;
  35611. this.updateFloat3 = this._updateFloat3ForUniform;
  35612. this.updateFloat4 = this._updateFloat4ForUniform;
  35613. this.updateMatrix = this._updateMatrixForUniform;
  35614. this.updateVector3 = this._updateVector3ForUniform;
  35615. this.updateVector4 = this._updateVector4ForUniform;
  35616. this.updateColor3 = this._updateColor3ForUniform;
  35617. this.updateColor4 = this._updateColor4ForUniform;
  35618. }
  35619. }
  35620. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35621. // Properties
  35622. /**
  35623. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35624. * or just falling back on setUniformXXX calls.
  35625. */
  35626. get: function () {
  35627. return !this._noUBO;
  35628. },
  35629. enumerable: true,
  35630. configurable: true
  35631. });
  35632. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35633. /**
  35634. * Indicates if the WebGL underlying uniform buffer is in sync
  35635. * with the javascript cache data.
  35636. */
  35637. get: function () {
  35638. return !this._needSync;
  35639. },
  35640. enumerable: true,
  35641. configurable: true
  35642. });
  35643. /**
  35644. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35645. * Also, a dynamic UniformBuffer will disable cache verification and always
  35646. * update the underlying WebGL uniform buffer to the GPU.
  35647. */
  35648. UniformBuffer.prototype.isDynamic = function () {
  35649. return this._dynamic !== undefined;
  35650. };
  35651. /**
  35652. * The data cache on JS side.
  35653. */
  35654. UniformBuffer.prototype.getData = function () {
  35655. return this._bufferData;
  35656. };
  35657. /**
  35658. * The underlying WebGL Uniform buffer.
  35659. */
  35660. UniformBuffer.prototype.getBuffer = function () {
  35661. return this._buffer;
  35662. };
  35663. /**
  35664. * std140 layout specifies how to align data within an UBO structure.
  35665. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35666. * for specs.
  35667. */
  35668. UniformBuffer.prototype._fillAlignment = function (size) {
  35669. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35670. // and 4x4 matrices
  35671. // TODO : change if other types are used
  35672. var alignment;
  35673. if (size <= 2) {
  35674. alignment = size;
  35675. }
  35676. else {
  35677. alignment = 4;
  35678. }
  35679. if ((this._uniformLocationPointer % alignment) !== 0) {
  35680. var oldPointer = this._uniformLocationPointer;
  35681. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35682. var diff = this._uniformLocationPointer - oldPointer;
  35683. for (var i = 0; i < diff; i++) {
  35684. this._data.push(0);
  35685. }
  35686. }
  35687. };
  35688. /**
  35689. * Adds an uniform in the buffer.
  35690. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35691. * for the layout to be correct !
  35692. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35693. * @param {number|number[]} size Data size, or data directly.
  35694. */
  35695. UniformBuffer.prototype.addUniform = function (name, size) {
  35696. if (this._noUBO) {
  35697. return;
  35698. }
  35699. if (this._uniformLocations[name] !== undefined) {
  35700. // Already existing uniform
  35701. return;
  35702. }
  35703. // This function must be called in the order of the shader layout !
  35704. // size can be the size of the uniform, or data directly
  35705. var data;
  35706. if (size instanceof Array) {
  35707. data = size;
  35708. size = data.length;
  35709. }
  35710. else {
  35711. size = size;
  35712. data = [];
  35713. // Fill with zeros
  35714. for (var i = 0; i < size; i++) {
  35715. data.push(0);
  35716. }
  35717. }
  35718. this._fillAlignment(size);
  35719. this._uniformSizes[name] = size;
  35720. this._uniformLocations[name] = this._uniformLocationPointer;
  35721. this._uniformLocationPointer += size;
  35722. for (var i = 0; i < size; i++) {
  35723. this._data.push(data[i]);
  35724. }
  35725. this._needSync = true;
  35726. };
  35727. /**
  35728. * Wrapper for addUniform.
  35729. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35730. * @param {Matrix} mat A 4x4 matrix.
  35731. */
  35732. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35733. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35734. };
  35735. /**
  35736. * Wrapper for addUniform.
  35737. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35738. * @param {number} x
  35739. * @param {number} y
  35740. */
  35741. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35742. var temp = [x, y];
  35743. this.addUniform(name, temp);
  35744. };
  35745. /**
  35746. * Wrapper for addUniform.
  35747. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35748. * @param {number} x
  35749. * @param {number} y
  35750. * @param {number} z
  35751. */
  35752. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35753. var temp = [x, y, z];
  35754. this.addUniform(name, temp);
  35755. };
  35756. /**
  35757. * Wrapper for addUniform.
  35758. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35759. * @param {Color3} color
  35760. */
  35761. UniformBuffer.prototype.addColor3 = function (name, color) {
  35762. var temp = new Array();
  35763. color.toArray(temp);
  35764. this.addUniform(name, temp);
  35765. };
  35766. /**
  35767. * Wrapper for addUniform.
  35768. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35769. * @param {Color3} color
  35770. * @param {number} alpha
  35771. */
  35772. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35773. var temp = new Array();
  35774. color.toArray(temp);
  35775. temp.push(alpha);
  35776. this.addUniform(name, temp);
  35777. };
  35778. /**
  35779. * Wrapper for addUniform.
  35780. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35781. * @param {Vector3} vector
  35782. */
  35783. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35784. var temp = new Array();
  35785. vector.toArray(temp);
  35786. this.addUniform(name, temp);
  35787. };
  35788. /**
  35789. * Wrapper for addUniform.
  35790. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35791. */
  35792. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35793. this.addUniform(name, 12);
  35794. };
  35795. /**
  35796. * Wrapper for addUniform.
  35797. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35798. */
  35799. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35800. this.addUniform(name, 8);
  35801. };
  35802. /**
  35803. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35804. */
  35805. UniformBuffer.prototype.create = function () {
  35806. if (this._noUBO) {
  35807. return;
  35808. }
  35809. if (this._buffer) {
  35810. return; // nothing to do
  35811. }
  35812. // See spec, alignment must be filled as a vec4
  35813. this._fillAlignment(4);
  35814. this._bufferData = new Float32Array(this._data);
  35815. this._rebuild();
  35816. this._needSync = true;
  35817. };
  35818. UniformBuffer.prototype._rebuild = function () {
  35819. if (this._noUBO) {
  35820. return;
  35821. }
  35822. if (this._dynamic) {
  35823. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35824. }
  35825. else {
  35826. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35827. }
  35828. };
  35829. /**
  35830. * Updates the WebGL Uniform Buffer on the GPU.
  35831. * If the `dynamic` flag is set to true, no cache comparison is done.
  35832. * Otherwise, the buffer will be updated only if the cache differs.
  35833. */
  35834. UniformBuffer.prototype.update = function () {
  35835. if (!this._buffer) {
  35836. this.create();
  35837. return;
  35838. }
  35839. if (!this._dynamic && !this._needSync) {
  35840. return;
  35841. }
  35842. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35843. this._needSync = false;
  35844. };
  35845. /**
  35846. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35847. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35848. * @param {number[]|Float32Array} data Flattened data
  35849. * @param {number} size Size of the data.
  35850. */
  35851. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35852. var location = this._uniformLocations[uniformName];
  35853. if (location === undefined) {
  35854. if (this._buffer) {
  35855. // Cannot add an uniform if the buffer is already created
  35856. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35857. return;
  35858. }
  35859. this.addUniform(uniformName, size);
  35860. location = this._uniformLocations[uniformName];
  35861. }
  35862. if (!this._buffer) {
  35863. this.create();
  35864. }
  35865. if (!this._dynamic) {
  35866. // Cache for static uniform buffers
  35867. var changed = false;
  35868. for (var i = 0; i < size; i++) {
  35869. if (this._bufferData[location + i] !== data[i]) {
  35870. changed = true;
  35871. this._bufferData[location + i] = data[i];
  35872. }
  35873. }
  35874. this._needSync = this._needSync || changed;
  35875. }
  35876. else {
  35877. // No cache for dynamic
  35878. for (var i = 0; i < size; i++) {
  35879. this._bufferData[location + i] = data[i];
  35880. }
  35881. }
  35882. };
  35883. // Update methods
  35884. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35885. // To match std140, matrix must be realigned
  35886. for (var i = 0; i < 3; i++) {
  35887. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35888. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35889. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35890. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35891. }
  35892. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35893. };
  35894. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35895. this._currentEffect.setMatrix3x3(name, matrix);
  35896. };
  35897. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35898. this._currentEffect.setMatrix2x2(name, matrix);
  35899. };
  35900. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35901. // To match std140, matrix must be realigned
  35902. for (var i = 0; i < 2; i++) {
  35903. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35904. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35905. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35906. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35907. }
  35908. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35909. };
  35910. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35911. this._currentEffect.setFloat(name, x);
  35912. };
  35913. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35914. UniformBuffer._tempBuffer[0] = x;
  35915. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35916. };
  35917. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35918. if (suffix === void 0) { suffix = ""; }
  35919. this._currentEffect.setFloat2(name + suffix, x, y);
  35920. };
  35921. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35922. if (suffix === void 0) { suffix = ""; }
  35923. UniformBuffer._tempBuffer[0] = x;
  35924. UniformBuffer._tempBuffer[1] = y;
  35925. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35926. };
  35927. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35928. if (suffix === void 0) { suffix = ""; }
  35929. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35930. };
  35931. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35932. if (suffix === void 0) { suffix = ""; }
  35933. UniformBuffer._tempBuffer[0] = x;
  35934. UniformBuffer._tempBuffer[1] = y;
  35935. UniformBuffer._tempBuffer[2] = z;
  35936. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35937. };
  35938. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35939. if (suffix === void 0) { suffix = ""; }
  35940. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35941. };
  35942. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35943. if (suffix === void 0) { suffix = ""; }
  35944. UniformBuffer._tempBuffer[0] = x;
  35945. UniformBuffer._tempBuffer[1] = y;
  35946. UniformBuffer._tempBuffer[2] = z;
  35947. UniformBuffer._tempBuffer[3] = w;
  35948. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35949. };
  35950. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35951. this._currentEffect.setMatrix(name, mat);
  35952. };
  35953. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35954. this.updateUniform(name, mat.toArray(), 16);
  35955. };
  35956. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35957. this._currentEffect.setVector3(name, vector);
  35958. };
  35959. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35960. vector.toArray(UniformBuffer._tempBuffer);
  35961. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35962. };
  35963. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35964. this._currentEffect.setVector4(name, vector);
  35965. };
  35966. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35967. vector.toArray(UniformBuffer._tempBuffer);
  35968. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35969. };
  35970. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35971. if (suffix === void 0) { suffix = ""; }
  35972. this._currentEffect.setColor3(name + suffix, color);
  35973. };
  35974. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35975. if (suffix === void 0) { suffix = ""; }
  35976. color.toArray(UniformBuffer._tempBuffer);
  35977. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35978. };
  35979. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35980. if (suffix === void 0) { suffix = ""; }
  35981. this._currentEffect.setColor4(name + suffix, color, alpha);
  35982. };
  35983. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35984. if (suffix === void 0) { suffix = ""; }
  35985. color.toArray(UniformBuffer._tempBuffer);
  35986. UniformBuffer._tempBuffer[3] = alpha;
  35987. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35988. };
  35989. /**
  35990. * Sets a sampler uniform on the effect.
  35991. * @param {string} name Name of the sampler.
  35992. * @param {Texture} texture
  35993. */
  35994. UniformBuffer.prototype.setTexture = function (name, texture) {
  35995. this._currentEffect.setTexture(name, texture);
  35996. };
  35997. /**
  35998. * Directly updates the value of the uniform in the cache AND on the GPU.
  35999. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36000. * @param {number[]|Float32Array} data Flattened data
  36001. */
  36002. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36003. this.updateUniform(uniformName, data, data.length);
  36004. this.update();
  36005. };
  36006. /**
  36007. * Binds this uniform buffer to an effect.
  36008. * @param {Effect} effect
  36009. * @param {string} name Name of the uniform block in the shader.
  36010. */
  36011. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36012. this._currentEffect = effect;
  36013. if (this._noUBO || !this._buffer) {
  36014. return;
  36015. }
  36016. effect.bindUniformBuffer(this._buffer, name);
  36017. };
  36018. /**
  36019. * Disposes the uniform buffer.
  36020. */
  36021. UniformBuffer.prototype.dispose = function () {
  36022. if (this._noUBO) {
  36023. return;
  36024. }
  36025. var index = this._engine._uniformBuffers.indexOf(this);
  36026. if (index !== -1) {
  36027. this._engine._uniformBuffers.splice(index, 1);
  36028. }
  36029. if (!this._buffer) {
  36030. return;
  36031. }
  36032. if (this._engine._releaseBuffer(this._buffer)) {
  36033. this._buffer = null;
  36034. }
  36035. };
  36036. // Pool for avoiding memory leaks
  36037. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36038. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36039. return UniformBuffer;
  36040. }());
  36041. BABYLON.UniformBuffer = UniformBuffer;
  36042. })(BABYLON || (BABYLON = {}));
  36043. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36044. var BABYLON;
  36045. (function (BABYLON) {
  36046. /**
  36047. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36048. */
  36049. var VertexData = /** @class */ (function () {
  36050. function VertexData() {
  36051. }
  36052. /**
  36053. * Uses the passed data array to set the set the values for the specified kind of data
  36054. * @param data a linear array of floating numbers
  36055. * @param kind the type of data that is being set, eg positions, colors etc
  36056. */
  36057. VertexData.prototype.set = function (data, kind) {
  36058. switch (kind) {
  36059. case BABYLON.VertexBuffer.PositionKind:
  36060. this.positions = data;
  36061. break;
  36062. case BABYLON.VertexBuffer.NormalKind:
  36063. this.normals = data;
  36064. break;
  36065. case BABYLON.VertexBuffer.TangentKind:
  36066. this.tangents = data;
  36067. break;
  36068. case BABYLON.VertexBuffer.UVKind:
  36069. this.uvs = data;
  36070. break;
  36071. case BABYLON.VertexBuffer.UV2Kind:
  36072. this.uvs2 = data;
  36073. break;
  36074. case BABYLON.VertexBuffer.UV3Kind:
  36075. this.uvs3 = data;
  36076. break;
  36077. case BABYLON.VertexBuffer.UV4Kind:
  36078. this.uvs4 = data;
  36079. break;
  36080. case BABYLON.VertexBuffer.UV5Kind:
  36081. this.uvs5 = data;
  36082. break;
  36083. case BABYLON.VertexBuffer.UV6Kind:
  36084. this.uvs6 = data;
  36085. break;
  36086. case BABYLON.VertexBuffer.ColorKind:
  36087. this.colors = data;
  36088. break;
  36089. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36090. this.matricesIndices = data;
  36091. break;
  36092. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36093. this.matricesWeights = data;
  36094. break;
  36095. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36096. this.matricesIndicesExtra = data;
  36097. break;
  36098. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36099. this.matricesWeightsExtra = data;
  36100. break;
  36101. }
  36102. };
  36103. /**
  36104. * Associates the vertexData to the passed Mesh.
  36105. * Sets it as updatable or not (default `false`)
  36106. * @param mesh the mesh the vertexData is applied to
  36107. * @param updatable when used and having the value true allows new data to update the vertexData
  36108. * @returns the VertexData
  36109. */
  36110. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36111. this._applyTo(mesh, updatable);
  36112. return this;
  36113. };
  36114. /**
  36115. * Associates the vertexData to the passed Geometry.
  36116. * Sets it as updatable or not (default `false`)
  36117. * @param geometry the geometry the vertexData is applied to
  36118. * @param updatable when used and having the value true allows new data to update the vertexData
  36119. * @returns VertexData
  36120. */
  36121. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36122. this._applyTo(geometry, updatable);
  36123. return this;
  36124. };
  36125. /**
  36126. * Updates the associated mesh
  36127. * @param mesh the mesh to be updated
  36128. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36129. * @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
  36130. * @returns VertexData
  36131. */
  36132. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36133. this._update(mesh);
  36134. return this;
  36135. };
  36136. /**
  36137. * Updates the associated geometry
  36138. * @param geometry the geometry to be updated
  36139. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36140. * @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
  36141. * @returns VertexData.
  36142. */
  36143. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36144. this._update(geometry);
  36145. return this;
  36146. };
  36147. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36148. if (updatable === void 0) { updatable = false; }
  36149. if (this.positions) {
  36150. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36151. }
  36152. if (this.normals) {
  36153. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36154. }
  36155. if (this.tangents) {
  36156. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36157. }
  36158. if (this.uvs) {
  36159. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36160. }
  36161. if (this.uvs2) {
  36162. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36163. }
  36164. if (this.uvs3) {
  36165. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36166. }
  36167. if (this.uvs4) {
  36168. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36169. }
  36170. if (this.uvs5) {
  36171. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36172. }
  36173. if (this.uvs6) {
  36174. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36175. }
  36176. if (this.colors) {
  36177. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36178. }
  36179. if (this.matricesIndices) {
  36180. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36181. }
  36182. if (this.matricesWeights) {
  36183. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36184. }
  36185. if (this.matricesIndicesExtra) {
  36186. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36187. }
  36188. if (this.matricesWeightsExtra) {
  36189. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36190. }
  36191. if (this.indices) {
  36192. meshOrGeometry.setIndices(this.indices, null, updatable);
  36193. }
  36194. else {
  36195. meshOrGeometry.setIndices([], null);
  36196. }
  36197. return this;
  36198. };
  36199. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36200. if (this.positions) {
  36201. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36202. }
  36203. if (this.normals) {
  36204. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36205. }
  36206. if (this.tangents) {
  36207. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36208. }
  36209. if (this.uvs) {
  36210. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36211. }
  36212. if (this.uvs2) {
  36213. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36214. }
  36215. if (this.uvs3) {
  36216. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36217. }
  36218. if (this.uvs4) {
  36219. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36220. }
  36221. if (this.uvs5) {
  36222. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36223. }
  36224. if (this.uvs6) {
  36225. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36226. }
  36227. if (this.colors) {
  36228. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36229. }
  36230. if (this.matricesIndices) {
  36231. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36232. }
  36233. if (this.matricesWeights) {
  36234. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36235. }
  36236. if (this.matricesIndicesExtra) {
  36237. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36238. }
  36239. if (this.matricesWeightsExtra) {
  36240. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36241. }
  36242. if (this.indices) {
  36243. meshOrGeometry.setIndices(this.indices, null);
  36244. }
  36245. return this;
  36246. };
  36247. /**
  36248. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36249. * @param matrix the transforming matrix
  36250. * @returns the VertexData
  36251. */
  36252. VertexData.prototype.transform = function (matrix) {
  36253. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36254. var transformed = BABYLON.Vector3.Zero();
  36255. var index;
  36256. if (this.positions) {
  36257. var position = BABYLON.Vector3.Zero();
  36258. for (index = 0; index < this.positions.length; index += 3) {
  36259. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36260. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36261. this.positions[index] = transformed.x;
  36262. this.positions[index + 1] = transformed.y;
  36263. this.positions[index + 2] = transformed.z;
  36264. }
  36265. }
  36266. if (this.normals) {
  36267. var normal = BABYLON.Vector3.Zero();
  36268. for (index = 0; index < this.normals.length; index += 3) {
  36269. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36270. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36271. this.normals[index] = transformed.x;
  36272. this.normals[index + 1] = transformed.y;
  36273. this.normals[index + 2] = transformed.z;
  36274. }
  36275. }
  36276. if (this.tangents) {
  36277. var tangent = BABYLON.Vector4.Zero();
  36278. var tangentTransformed = BABYLON.Vector4.Zero();
  36279. for (index = 0; index < this.tangents.length; index += 4) {
  36280. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36281. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36282. this.tangents[index] = tangentTransformed.x;
  36283. this.tangents[index + 1] = tangentTransformed.y;
  36284. this.tangents[index + 2] = tangentTransformed.z;
  36285. this.tangents[index + 3] = tangentTransformed.w;
  36286. }
  36287. }
  36288. if (flip && this.indices) {
  36289. for (index = 0; index < this.indices.length; index += 3) {
  36290. var tmp = this.indices[index + 1];
  36291. this.indices[index + 1] = this.indices[index + 2];
  36292. this.indices[index + 2] = tmp;
  36293. }
  36294. }
  36295. return this;
  36296. };
  36297. /**
  36298. * Merges the passed VertexData into the current one
  36299. * @param other the VertexData to be merged into the current one
  36300. * @returns the modified VertexData
  36301. */
  36302. VertexData.prototype.merge = function (other) {
  36303. this._validate();
  36304. other._validate();
  36305. if (!this.normals !== !other.normals ||
  36306. !this.tangents !== !other.tangents ||
  36307. !this.uvs !== !other.uvs ||
  36308. !this.uvs2 !== !other.uvs2 ||
  36309. !this.uvs3 !== !other.uvs3 ||
  36310. !this.uvs4 !== !other.uvs4 ||
  36311. !this.uvs5 !== !other.uvs5 ||
  36312. !this.uvs6 !== !other.uvs6 ||
  36313. !this.colors !== !other.colors ||
  36314. !this.matricesIndices !== !other.matricesIndices ||
  36315. !this.matricesWeights !== !other.matricesWeights ||
  36316. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36317. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36318. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36319. }
  36320. if (other.indices) {
  36321. if (!this.indices) {
  36322. this.indices = [];
  36323. }
  36324. var offset = this.positions ? this.positions.length / 3 : 0;
  36325. for (var index = 0; index < other.indices.length; index++) {
  36326. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36327. this.indices.push(other.indices[index] + offset);
  36328. }
  36329. }
  36330. this.positions = this._mergeElement(this.positions, other.positions);
  36331. this.normals = this._mergeElement(this.normals, other.normals);
  36332. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36333. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36334. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36335. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36336. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36337. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36338. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36339. this.colors = this._mergeElement(this.colors, other.colors);
  36340. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36341. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36342. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36343. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36344. return this;
  36345. };
  36346. VertexData.prototype._mergeElement = function (source, other) {
  36347. if (!source) {
  36348. return other;
  36349. }
  36350. if (!other) {
  36351. return source;
  36352. }
  36353. var len = other.length + source.length;
  36354. var isSrcTypedArray = source instanceof Float32Array;
  36355. var isOthTypedArray = other instanceof Float32Array;
  36356. // use non-loop method when the source is Float32Array
  36357. if (isSrcTypedArray) {
  36358. var ret32 = new Float32Array(len);
  36359. ret32.set(source);
  36360. ret32.set(other, source.length);
  36361. return ret32;
  36362. // source is number[], when other is also use concat
  36363. }
  36364. else if (!isOthTypedArray) {
  36365. return source.concat(other);
  36366. // source is a number[], but other is a Float32Array, loop required
  36367. }
  36368. else {
  36369. var ret = source.slice(0); // copy source to a separate array
  36370. for (var i = 0, len = other.length; i < len; i++) {
  36371. ret.push(other[i]);
  36372. }
  36373. return ret;
  36374. }
  36375. };
  36376. VertexData.prototype._validate = function () {
  36377. if (!this.positions) {
  36378. throw new Error("Positions are required");
  36379. }
  36380. var getElementCount = function (kind, values) {
  36381. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36382. if ((values.length % stride) !== 0) {
  36383. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36384. }
  36385. return values.length / stride;
  36386. };
  36387. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36388. var validateElementCount = function (kind, values) {
  36389. var elementCount = getElementCount(kind, values);
  36390. if (elementCount !== positionsElementCount) {
  36391. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36392. }
  36393. };
  36394. if (this.normals)
  36395. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36396. if (this.tangents)
  36397. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36398. if (this.uvs)
  36399. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36400. if (this.uvs2)
  36401. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36402. if (this.uvs3)
  36403. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36404. if (this.uvs4)
  36405. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36406. if (this.uvs5)
  36407. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36408. if (this.uvs6)
  36409. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36410. if (this.colors)
  36411. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36412. if (this.matricesIndices)
  36413. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36414. if (this.matricesWeights)
  36415. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36416. if (this.matricesIndicesExtra)
  36417. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36418. if (this.matricesWeightsExtra)
  36419. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36420. };
  36421. /**
  36422. * Serializes the VertexData
  36423. * @returns a serialized object
  36424. */
  36425. VertexData.prototype.serialize = function () {
  36426. var serializationObject = this.serialize();
  36427. if (this.positions) {
  36428. serializationObject.positions = this.positions;
  36429. }
  36430. if (this.normals) {
  36431. serializationObject.normals = this.normals;
  36432. }
  36433. if (this.tangents) {
  36434. serializationObject.tangents = this.tangents;
  36435. }
  36436. if (this.uvs) {
  36437. serializationObject.uvs = this.uvs;
  36438. }
  36439. if (this.uvs2) {
  36440. serializationObject.uvs2 = this.uvs2;
  36441. }
  36442. if (this.uvs3) {
  36443. serializationObject.uvs3 = this.uvs3;
  36444. }
  36445. if (this.uvs4) {
  36446. serializationObject.uvs4 = this.uvs4;
  36447. }
  36448. if (this.uvs5) {
  36449. serializationObject.uvs5 = this.uvs5;
  36450. }
  36451. if (this.uvs6) {
  36452. serializationObject.uvs6 = this.uvs6;
  36453. }
  36454. if (this.colors) {
  36455. serializationObject.colors = this.colors;
  36456. }
  36457. if (this.matricesIndices) {
  36458. serializationObject.matricesIndices = this.matricesIndices;
  36459. serializationObject.matricesIndices._isExpanded = true;
  36460. }
  36461. if (this.matricesWeights) {
  36462. serializationObject.matricesWeights = this.matricesWeights;
  36463. }
  36464. if (this.matricesIndicesExtra) {
  36465. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36466. serializationObject.matricesIndicesExtra._isExpanded = true;
  36467. }
  36468. if (this.matricesWeightsExtra) {
  36469. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36470. }
  36471. serializationObject.indices = this.indices;
  36472. return serializationObject;
  36473. };
  36474. // Statics
  36475. /**
  36476. * Extracts the vertexData from a mesh
  36477. * @param mesh the mesh from which to extract the VertexData
  36478. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36479. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36480. * @returns the object VertexData associated to the passed mesh
  36481. */
  36482. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36483. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36484. };
  36485. /**
  36486. * Extracts the vertexData from the geometry
  36487. * @param geometry the geometry from which to extract the VertexData
  36488. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36489. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36490. * @returns the object VertexData associated to the passed mesh
  36491. */
  36492. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36493. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36494. };
  36495. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36496. var result = new VertexData();
  36497. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36498. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36499. }
  36500. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36501. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36502. }
  36503. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36504. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36505. }
  36506. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36507. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36508. }
  36509. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36510. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36511. }
  36512. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36513. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36514. }
  36515. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36516. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36517. }
  36518. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36519. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36520. }
  36521. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36522. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36523. }
  36524. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36525. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36526. }
  36527. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36528. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36529. }
  36530. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36531. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36532. }
  36533. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36534. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36535. }
  36536. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36537. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36538. }
  36539. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36540. return result;
  36541. };
  36542. /**
  36543. * Creates the VertexData for a Ribbon
  36544. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36545. * * pathArray array of paths, each of which an array of successive Vector3
  36546. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36547. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36548. * * 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
  36549. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36550. * * 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)
  36551. * * 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)
  36552. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36553. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36554. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36555. * @returns the VertexData of the ribbon
  36556. */
  36557. VertexData.CreateRibbon = function (options) {
  36558. var pathArray = options.pathArray;
  36559. var closeArray = options.closeArray || false;
  36560. var closePath = options.closePath || false;
  36561. var invertUV = options.invertUV || false;
  36562. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36563. var offset = options.offset || defaultOffset;
  36564. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36565. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36566. var customUV = options.uvs;
  36567. var customColors = options.colors;
  36568. var positions = [];
  36569. var indices = [];
  36570. var normals = [];
  36571. var uvs = [];
  36572. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36573. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36574. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36575. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36576. var minlg; // minimal length among all paths from pathArray
  36577. var lg = []; // array of path lengths : nb of vertex per path
  36578. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36579. var p; // path iterator
  36580. var i; // point iterator
  36581. var j; // point iterator
  36582. // if single path in pathArray
  36583. if (pathArray.length < 2) {
  36584. var ar1 = [];
  36585. var ar2 = [];
  36586. for (i = 0; i < pathArray[0].length - offset; i++) {
  36587. ar1.push(pathArray[0][i]);
  36588. ar2.push(pathArray[0][i + offset]);
  36589. }
  36590. pathArray = [ar1, ar2];
  36591. }
  36592. // positions and horizontal distances (u)
  36593. var idc = 0;
  36594. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36595. var path;
  36596. var l;
  36597. minlg = pathArray[0].length;
  36598. var vectlg;
  36599. var dist;
  36600. for (p = 0; p < pathArray.length; p++) {
  36601. uTotalDistance[p] = 0;
  36602. us[p] = [0];
  36603. path = pathArray[p];
  36604. l = path.length;
  36605. minlg = (minlg < l) ? minlg : l;
  36606. j = 0;
  36607. while (j < l) {
  36608. positions.push(path[j].x, path[j].y, path[j].z);
  36609. if (j > 0) {
  36610. vectlg = path[j].subtract(path[j - 1]).length();
  36611. dist = vectlg + uTotalDistance[p];
  36612. us[p].push(dist);
  36613. uTotalDistance[p] = dist;
  36614. }
  36615. j++;
  36616. }
  36617. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36618. j--;
  36619. positions.push(path[0].x, path[0].y, path[0].z);
  36620. vectlg = path[j].subtract(path[0]).length();
  36621. dist = vectlg + uTotalDistance[p];
  36622. us[p].push(dist);
  36623. uTotalDistance[p] = dist;
  36624. }
  36625. lg[p] = l + closePathCorr;
  36626. idx[p] = idc;
  36627. idc += (l + closePathCorr);
  36628. }
  36629. // vertical distances (v)
  36630. var path1;
  36631. var path2;
  36632. var vertex1 = null;
  36633. var vertex2 = null;
  36634. for (i = 0; i < minlg + closePathCorr; i++) {
  36635. vTotalDistance[i] = 0;
  36636. vs[i] = [0];
  36637. for (p = 0; p < pathArray.length - 1; p++) {
  36638. path1 = pathArray[p];
  36639. path2 = pathArray[p + 1];
  36640. if (i === minlg) { // closePath
  36641. vertex1 = path1[0];
  36642. vertex2 = path2[0];
  36643. }
  36644. else {
  36645. vertex1 = path1[i];
  36646. vertex2 = path2[i];
  36647. }
  36648. vectlg = vertex2.subtract(vertex1).length();
  36649. dist = vectlg + vTotalDistance[i];
  36650. vs[i].push(dist);
  36651. vTotalDistance[i] = dist;
  36652. }
  36653. if (closeArray && vertex2 && vertex1) {
  36654. path1 = pathArray[p];
  36655. path2 = pathArray[0];
  36656. if (i === minlg) { // closePath
  36657. vertex2 = path2[0];
  36658. }
  36659. vectlg = vertex2.subtract(vertex1).length();
  36660. dist = vectlg + vTotalDistance[i];
  36661. vTotalDistance[i] = dist;
  36662. }
  36663. }
  36664. // uvs
  36665. var u;
  36666. var v;
  36667. if (customUV) {
  36668. for (p = 0; p < customUV.length; p++) {
  36669. uvs.push(customUV[p].x, customUV[p].y);
  36670. }
  36671. }
  36672. else {
  36673. for (p = 0; p < pathArray.length; p++) {
  36674. for (i = 0; i < minlg + closePathCorr; i++) {
  36675. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36676. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36677. if (invertUV) {
  36678. uvs.push(v, u);
  36679. }
  36680. else {
  36681. uvs.push(u, v);
  36682. }
  36683. }
  36684. }
  36685. }
  36686. // indices
  36687. p = 0; // path index
  36688. var pi = 0; // positions array index
  36689. var l1 = lg[p] - 1; // path1 length
  36690. var l2 = lg[p + 1] - 1; // path2 length
  36691. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36692. var shft = idx[1] - idx[0]; // shift
  36693. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36694. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36695. // 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
  36696. indices.push(pi, pi + shft, pi + 1);
  36697. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36698. pi += 1;
  36699. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36700. p++;
  36701. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36702. shft = idx[0] - idx[p];
  36703. l1 = lg[p] - 1;
  36704. l2 = lg[0] - 1;
  36705. }
  36706. else {
  36707. shft = idx[p + 1] - idx[p];
  36708. l1 = lg[p] - 1;
  36709. l2 = lg[p + 1] - 1;
  36710. }
  36711. pi = idx[p];
  36712. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36713. }
  36714. }
  36715. // normals
  36716. VertexData.ComputeNormals(positions, indices, normals);
  36717. if (closePath) { // update both the first and last vertex normals to their average value
  36718. var indexFirst = 0;
  36719. var indexLast = 0;
  36720. for (p = 0; p < pathArray.length; p++) {
  36721. indexFirst = idx[p] * 3;
  36722. if (p + 1 < pathArray.length) {
  36723. indexLast = (idx[p + 1] - 1) * 3;
  36724. }
  36725. else {
  36726. indexLast = normals.length - 3;
  36727. }
  36728. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36729. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36730. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36731. normals[indexLast] = normals[indexFirst];
  36732. normals[indexLast + 1] = normals[indexFirst + 1];
  36733. normals[indexLast + 2] = normals[indexFirst + 2];
  36734. }
  36735. }
  36736. // sides
  36737. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36738. // Colors
  36739. var colors = null;
  36740. if (customColors) {
  36741. colors = new Float32Array(customColors.length * 4);
  36742. for (var c = 0; c < customColors.length; c++) {
  36743. colors[c * 4] = customColors[c].r;
  36744. colors[c * 4 + 1] = customColors[c].g;
  36745. colors[c * 4 + 2] = customColors[c].b;
  36746. colors[c * 4 + 3] = customColors[c].a;
  36747. }
  36748. }
  36749. // Result
  36750. var vertexData = new VertexData();
  36751. var positions32 = new Float32Array(positions);
  36752. var normals32 = new Float32Array(normals);
  36753. var uvs32 = new Float32Array(uvs);
  36754. vertexData.indices = indices;
  36755. vertexData.positions = positions32;
  36756. vertexData.normals = normals32;
  36757. vertexData.uvs = uvs32;
  36758. if (colors) {
  36759. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36760. }
  36761. if (closePath) {
  36762. vertexData._idx = idx;
  36763. }
  36764. return vertexData;
  36765. };
  36766. /**
  36767. * Creates the VertexData for a box
  36768. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36769. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36770. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36771. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36772. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36773. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36774. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36775. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36776. * * 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)
  36777. * * 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)
  36778. * @returns the VertexData of the box
  36779. */
  36780. VertexData.CreateBox = function (options) {
  36781. var normalsSource = [
  36782. new BABYLON.Vector3(0, 0, 1),
  36783. new BABYLON.Vector3(0, 0, -1),
  36784. new BABYLON.Vector3(1, 0, 0),
  36785. new BABYLON.Vector3(-1, 0, 0),
  36786. new BABYLON.Vector3(0, 1, 0),
  36787. new BABYLON.Vector3(0, -1, 0)
  36788. ];
  36789. var indices = [];
  36790. var positions = [];
  36791. var normals = [];
  36792. var uvs = [];
  36793. var width = options.width || options.size || 1;
  36794. var height = options.height || options.size || 1;
  36795. var depth = options.depth || options.size || 1;
  36796. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36797. var faceUV = options.faceUV || new Array(6);
  36798. var faceColors = options.faceColors;
  36799. var colors = [];
  36800. // default face colors and UV if undefined
  36801. for (var f = 0; f < 6; f++) {
  36802. if (faceUV[f] === undefined) {
  36803. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36804. }
  36805. if (faceColors && faceColors[f] === undefined) {
  36806. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36807. }
  36808. }
  36809. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36810. // Create each face in turn.
  36811. for (var index = 0; index < normalsSource.length; index++) {
  36812. var normal = normalsSource[index];
  36813. // Get two vectors perpendicular to the face normal and to each other.
  36814. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36815. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36816. // Six indices (two triangles) per face.
  36817. var verticesLength = positions.length / 3;
  36818. indices.push(verticesLength);
  36819. indices.push(verticesLength + 1);
  36820. indices.push(verticesLength + 2);
  36821. indices.push(verticesLength);
  36822. indices.push(verticesLength + 2);
  36823. indices.push(verticesLength + 3);
  36824. // Four vertices per face.
  36825. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36826. positions.push(vertex.x, vertex.y, vertex.z);
  36827. normals.push(normal.x, normal.y, normal.z);
  36828. uvs.push(faceUV[index].z, faceUV[index].w);
  36829. if (faceColors) {
  36830. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36831. }
  36832. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36833. positions.push(vertex.x, vertex.y, vertex.z);
  36834. normals.push(normal.x, normal.y, normal.z);
  36835. uvs.push(faceUV[index].x, faceUV[index].w);
  36836. if (faceColors) {
  36837. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36838. }
  36839. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36840. positions.push(vertex.x, vertex.y, vertex.z);
  36841. normals.push(normal.x, normal.y, normal.z);
  36842. uvs.push(faceUV[index].x, faceUV[index].y);
  36843. if (faceColors) {
  36844. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36845. }
  36846. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36847. positions.push(vertex.x, vertex.y, vertex.z);
  36848. normals.push(normal.x, normal.y, normal.z);
  36849. uvs.push(faceUV[index].z, faceUV[index].y);
  36850. if (faceColors) {
  36851. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36852. }
  36853. }
  36854. // sides
  36855. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36856. // Result
  36857. var vertexData = new VertexData();
  36858. vertexData.indices = indices;
  36859. vertexData.positions = positions;
  36860. vertexData.normals = normals;
  36861. vertexData.uvs = uvs;
  36862. if (faceColors) {
  36863. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36864. vertexData.colors = totalColors;
  36865. }
  36866. return vertexData;
  36867. };
  36868. /**
  36869. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36870. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36871. * * segments sets the number of horizontal strips optional, default 32
  36872. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36873. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36874. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36875. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36876. * * 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
  36877. * * 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
  36878. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36879. * * 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)
  36880. * * 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)
  36881. * @returns the VertexData of the ellipsoid
  36882. */
  36883. VertexData.CreateSphere = function (options) {
  36884. var segments = options.segments || 32;
  36885. var diameterX = options.diameterX || options.diameter || 1;
  36886. var diameterY = options.diameterY || options.diameter || 1;
  36887. var diameterZ = options.diameterZ || options.diameter || 1;
  36888. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36889. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36890. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36891. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36892. var totalZRotationSteps = 2 + segments;
  36893. var totalYRotationSteps = 2 * totalZRotationSteps;
  36894. var indices = [];
  36895. var positions = [];
  36896. var normals = [];
  36897. var uvs = [];
  36898. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36899. var normalizedZ = zRotationStep / totalZRotationSteps;
  36900. var angleZ = normalizedZ * Math.PI * slice;
  36901. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36902. var normalizedY = yRotationStep / totalYRotationSteps;
  36903. var angleY = normalizedY * Math.PI * 2 * arc;
  36904. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36905. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36906. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36907. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36908. var vertex = complete.multiply(radius);
  36909. var normal = complete.divide(radius).normalize();
  36910. positions.push(vertex.x, vertex.y, vertex.z);
  36911. normals.push(normal.x, normal.y, normal.z);
  36912. uvs.push(normalizedY, normalizedZ);
  36913. }
  36914. if (zRotationStep > 0) {
  36915. var verticesCount = positions.length / 3;
  36916. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36917. indices.push((firstIndex));
  36918. indices.push((firstIndex + 1));
  36919. indices.push(firstIndex + totalYRotationSteps + 1);
  36920. indices.push((firstIndex + totalYRotationSteps + 1));
  36921. indices.push((firstIndex + 1));
  36922. indices.push((firstIndex + totalYRotationSteps + 2));
  36923. }
  36924. }
  36925. }
  36926. // Sides
  36927. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36928. // Result
  36929. var vertexData = new VertexData();
  36930. vertexData.indices = indices;
  36931. vertexData.positions = positions;
  36932. vertexData.normals = normals;
  36933. vertexData.uvs = uvs;
  36934. return vertexData;
  36935. };
  36936. /**
  36937. * Creates the VertexData for a cylinder, cone or prism
  36938. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36939. * * height sets the height (y direction) of the cylinder, optional, default 2
  36940. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36941. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36942. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36943. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36944. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36945. * * 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
  36946. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36947. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36948. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36949. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36950. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36951. * * 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)
  36952. * * 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)
  36953. * @returns the VertexData of the cylinder, cone or prism
  36954. */
  36955. VertexData.CreateCylinder = function (options) {
  36956. var height = options.height || 2;
  36957. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36958. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36959. var tessellation = options.tessellation || 24;
  36960. var subdivisions = options.subdivisions || 1;
  36961. var hasRings = options.hasRings ? true : false;
  36962. var enclose = options.enclose ? true : false;
  36963. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36964. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36965. var faceUV = options.faceUV || new Array(3);
  36966. var faceColors = options.faceColors;
  36967. // default face colors and UV if undefined
  36968. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36969. var ringNb = (hasRings) ? subdivisions : 1;
  36970. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36971. var f;
  36972. for (f = 0; f < surfaceNb; f++) {
  36973. if (faceColors && faceColors[f] === undefined) {
  36974. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36975. }
  36976. }
  36977. for (f = 0; f < surfaceNb; f++) {
  36978. if (faceUV && faceUV[f] === undefined) {
  36979. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36980. }
  36981. }
  36982. var indices = new Array();
  36983. var positions = new Array();
  36984. var normals = new Array();
  36985. var uvs = new Array();
  36986. var colors = new Array();
  36987. var angle_step = Math.PI * 2 * arc / tessellation;
  36988. var angle;
  36989. var h;
  36990. var radius;
  36991. var tan = (diameterBottom - diameterTop) / 2 / height;
  36992. var ringVertex = BABYLON.Vector3.Zero();
  36993. var ringNormal = BABYLON.Vector3.Zero();
  36994. var ringFirstVertex = BABYLON.Vector3.Zero();
  36995. var ringFirstNormal = BABYLON.Vector3.Zero();
  36996. var quadNormal = BABYLON.Vector3.Zero();
  36997. var Y = BABYLON.Axis.Y;
  36998. // positions, normals, uvs
  36999. var i;
  37000. var j;
  37001. var r;
  37002. var ringIdx = 1;
  37003. var s = 1; // surface index
  37004. var cs = 0;
  37005. var v = 0;
  37006. for (i = 0; i <= subdivisions; i++) {
  37007. h = i / subdivisions;
  37008. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37009. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37010. for (r = 0; r < ringIdx; r++) {
  37011. if (hasRings) {
  37012. s += r;
  37013. }
  37014. if (enclose) {
  37015. s += 2 * r;
  37016. }
  37017. for (j = 0; j <= tessellation; j++) {
  37018. angle = j * angle_step;
  37019. // position
  37020. ringVertex.x = Math.cos(-angle) * radius;
  37021. ringVertex.y = -height / 2 + h * height;
  37022. ringVertex.z = Math.sin(-angle) * radius;
  37023. // normal
  37024. if (diameterTop === 0 && i === subdivisions) {
  37025. // if no top cap, reuse former normals
  37026. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37027. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37028. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37029. }
  37030. else {
  37031. ringNormal.x = ringVertex.x;
  37032. ringNormal.z = ringVertex.z;
  37033. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37034. ringNormal.normalize();
  37035. }
  37036. // keep first ring vertex values for enclose
  37037. if (j === 0) {
  37038. ringFirstVertex.copyFrom(ringVertex);
  37039. ringFirstNormal.copyFrom(ringNormal);
  37040. }
  37041. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37042. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37043. if (hasRings) {
  37044. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37045. }
  37046. else {
  37047. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37048. }
  37049. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37050. if (faceColors) {
  37051. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37052. }
  37053. }
  37054. // if enclose, add four vertices and their dedicated normals
  37055. if (arc !== 1 && enclose) {
  37056. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37057. positions.push(0, ringVertex.y, 0);
  37058. positions.push(0, ringVertex.y, 0);
  37059. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37060. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37061. quadNormal.normalize();
  37062. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37063. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37064. quadNormal.normalize();
  37065. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37066. if (hasRings) {
  37067. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37068. }
  37069. else {
  37070. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37071. }
  37072. uvs.push(faceUV[s + 1].x, v);
  37073. uvs.push(faceUV[s + 1].z, v);
  37074. if (hasRings) {
  37075. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37076. }
  37077. else {
  37078. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37079. }
  37080. uvs.push(faceUV[s + 2].x, v);
  37081. uvs.push(faceUV[s + 2].z, v);
  37082. if (faceColors) {
  37083. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37084. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37085. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37086. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37087. }
  37088. }
  37089. if (cs !== s) {
  37090. cs = s;
  37091. }
  37092. }
  37093. }
  37094. // indices
  37095. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37096. var s;
  37097. i = 0;
  37098. for (s = 0; s < subdivisions; s++) {
  37099. var i0 = 0;
  37100. var i1 = 0;
  37101. var i2 = 0;
  37102. var i3 = 0;
  37103. for (j = 0; j < tessellation; j++) {
  37104. i0 = i * (e + 1) + j;
  37105. i1 = (i + 1) * (e + 1) + j;
  37106. i2 = i * (e + 1) + (j + 1);
  37107. i3 = (i + 1) * (e + 1) + (j + 1);
  37108. indices.push(i0, i1, i2);
  37109. indices.push(i3, i2, i1);
  37110. }
  37111. if (arc !== 1 && enclose) { // if enclose, add two quads
  37112. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37113. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37114. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37115. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37116. }
  37117. i = (hasRings) ? (i + 2) : (i + 1);
  37118. }
  37119. // Caps
  37120. var createCylinderCap = function (isTop) {
  37121. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37122. if (radius === 0) {
  37123. return;
  37124. }
  37125. // Cap positions, normals & uvs
  37126. var angle;
  37127. var circleVector;
  37128. var i;
  37129. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37130. var c = null;
  37131. if (faceColors) {
  37132. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37133. }
  37134. // cap center
  37135. var vbase = positions.length / 3;
  37136. var offset = isTop ? height / 2 : -height / 2;
  37137. var center = new BABYLON.Vector3(0, offset, 0);
  37138. positions.push(center.x, center.y, center.z);
  37139. normals.push(0, isTop ? 1 : -1, 0);
  37140. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37141. if (c) {
  37142. colors.push(c.r, c.g, c.b, c.a);
  37143. }
  37144. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37145. for (i = 0; i <= tessellation; i++) {
  37146. angle = Math.PI * 2 * i * arc / tessellation;
  37147. var cos = Math.cos(-angle);
  37148. var sin = Math.sin(-angle);
  37149. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37150. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37151. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37152. normals.push(0, isTop ? 1 : -1, 0);
  37153. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37154. if (c) {
  37155. colors.push(c.r, c.g, c.b, c.a);
  37156. }
  37157. }
  37158. // Cap indices
  37159. for (i = 0; i < tessellation; i++) {
  37160. if (!isTop) {
  37161. indices.push(vbase);
  37162. indices.push(vbase + (i + 1));
  37163. indices.push(vbase + (i + 2));
  37164. }
  37165. else {
  37166. indices.push(vbase);
  37167. indices.push(vbase + (i + 2));
  37168. indices.push(vbase + (i + 1));
  37169. }
  37170. }
  37171. };
  37172. // add caps to geometry
  37173. createCylinderCap(false);
  37174. createCylinderCap(true);
  37175. // Sides
  37176. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37177. var vertexData = new VertexData();
  37178. vertexData.indices = indices;
  37179. vertexData.positions = positions;
  37180. vertexData.normals = normals;
  37181. vertexData.uvs = uvs;
  37182. if (faceColors) {
  37183. vertexData.colors = colors;
  37184. }
  37185. return vertexData;
  37186. };
  37187. /**
  37188. * Creates the VertexData for a torus
  37189. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37190. * * diameter the diameter of the torus, optional default 1
  37191. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37192. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37193. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37194. * * 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)
  37195. * * 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)
  37196. * @returns the VertexData of the torus
  37197. */
  37198. VertexData.CreateTorus = function (options) {
  37199. var indices = [];
  37200. var positions = [];
  37201. var normals = [];
  37202. var uvs = [];
  37203. var diameter = options.diameter || 1;
  37204. var thickness = options.thickness || 0.5;
  37205. var tessellation = options.tessellation || 16;
  37206. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37207. var stride = tessellation + 1;
  37208. for (var i = 0; i <= tessellation; i++) {
  37209. var u = i / tessellation;
  37210. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37211. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37212. for (var j = 0; j <= tessellation; j++) {
  37213. var v = 1 - j / tessellation;
  37214. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37215. var dx = Math.cos(innerAngle);
  37216. var dy = Math.sin(innerAngle);
  37217. // Create a vertex.
  37218. var normal = new BABYLON.Vector3(dx, dy, 0);
  37219. var position = normal.scale(thickness / 2);
  37220. var textureCoordinate = new BABYLON.Vector2(u, v);
  37221. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37222. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37223. positions.push(position.x, position.y, position.z);
  37224. normals.push(normal.x, normal.y, normal.z);
  37225. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37226. // And create indices for two triangles.
  37227. var nextI = (i + 1) % stride;
  37228. var nextJ = (j + 1) % stride;
  37229. indices.push(i * stride + j);
  37230. indices.push(i * stride + nextJ);
  37231. indices.push(nextI * stride + j);
  37232. indices.push(i * stride + nextJ);
  37233. indices.push(nextI * stride + nextJ);
  37234. indices.push(nextI * stride + j);
  37235. }
  37236. }
  37237. // Sides
  37238. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37239. // Result
  37240. var vertexData = new VertexData();
  37241. vertexData.indices = indices;
  37242. vertexData.positions = positions;
  37243. vertexData.normals = normals;
  37244. vertexData.uvs = uvs;
  37245. return vertexData;
  37246. };
  37247. /**
  37248. * Creates the VertexData of the LineSystem
  37249. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37250. * - lines an array of lines, each line being an array of successive Vector3
  37251. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37252. * @returns the VertexData of the LineSystem
  37253. */
  37254. VertexData.CreateLineSystem = function (options) {
  37255. var indices = [];
  37256. var positions = [];
  37257. var lines = options.lines;
  37258. var colors = options.colors;
  37259. var vertexColors = [];
  37260. var idx = 0;
  37261. for (var l = 0; l < lines.length; l++) {
  37262. var points = lines[l];
  37263. for (var index = 0; index < points.length; index++) {
  37264. positions.push(points[index].x, points[index].y, points[index].z);
  37265. if (colors) {
  37266. var color = colors[l];
  37267. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37268. }
  37269. if (index > 0) {
  37270. indices.push(idx - 1);
  37271. indices.push(idx);
  37272. }
  37273. idx++;
  37274. }
  37275. }
  37276. var vertexData = new VertexData();
  37277. vertexData.indices = indices;
  37278. vertexData.positions = positions;
  37279. if (colors) {
  37280. vertexData.colors = vertexColors;
  37281. }
  37282. return vertexData;
  37283. };
  37284. /**
  37285. * Create the VertexData for a DashedLines
  37286. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37287. * - points an array successive Vector3
  37288. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37289. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37290. * - dashNb the intended total number of dashes, optional, default 200
  37291. * @returns the VertexData for the DashedLines
  37292. */
  37293. VertexData.CreateDashedLines = function (options) {
  37294. var dashSize = options.dashSize || 3;
  37295. var gapSize = options.gapSize || 1;
  37296. var dashNb = options.dashNb || 200;
  37297. var points = options.points;
  37298. var positions = new Array();
  37299. var indices = new Array();
  37300. var curvect = BABYLON.Vector3.Zero();
  37301. var lg = 0;
  37302. var nb = 0;
  37303. var shft = 0;
  37304. var dashshft = 0;
  37305. var curshft = 0;
  37306. var idx = 0;
  37307. var i = 0;
  37308. for (i = 0; i < points.length - 1; i++) {
  37309. points[i + 1].subtractToRef(points[i], curvect);
  37310. lg += curvect.length();
  37311. }
  37312. shft = lg / dashNb;
  37313. dashshft = dashSize * shft / (dashSize + gapSize);
  37314. for (i = 0; i < points.length - 1; i++) {
  37315. points[i + 1].subtractToRef(points[i], curvect);
  37316. nb = Math.floor(curvect.length() / shft);
  37317. curvect.normalize();
  37318. for (var j = 0; j < nb; j++) {
  37319. curshft = shft * j;
  37320. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37321. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37322. indices.push(idx, idx + 1);
  37323. idx += 2;
  37324. }
  37325. }
  37326. // Result
  37327. var vertexData = new VertexData();
  37328. vertexData.positions = positions;
  37329. vertexData.indices = indices;
  37330. return vertexData;
  37331. };
  37332. /**
  37333. * Creates the VertexData for a Ground
  37334. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37335. * - width the width (x direction) of the ground, optional, default 1
  37336. * - height the height (z direction) of the ground, optional, default 1
  37337. * - subdivisions the number of subdivisions per side, optional, default 1
  37338. * @returns the VertexData of the Ground
  37339. */
  37340. VertexData.CreateGround = function (options) {
  37341. var indices = [];
  37342. var positions = [];
  37343. var normals = [];
  37344. var uvs = [];
  37345. var row, col;
  37346. var width = options.width || 1;
  37347. var height = options.height || 1;
  37348. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37349. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37350. for (row = 0; row <= subdivisionsY; row++) {
  37351. for (col = 0; col <= subdivisionsX; col++) {
  37352. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37353. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37354. positions.push(position.x, position.y, position.z);
  37355. normals.push(normal.x, normal.y, normal.z);
  37356. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37357. }
  37358. }
  37359. for (row = 0; row < subdivisionsY; row++) {
  37360. for (col = 0; col < subdivisionsX; col++) {
  37361. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37362. indices.push(col + 1 + row * (subdivisionsX + 1));
  37363. indices.push(col + row * (subdivisionsX + 1));
  37364. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37365. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37366. indices.push(col + row * (subdivisionsX + 1));
  37367. }
  37368. }
  37369. // Result
  37370. var vertexData = new VertexData();
  37371. vertexData.indices = indices;
  37372. vertexData.positions = positions;
  37373. vertexData.normals = normals;
  37374. vertexData.uvs = uvs;
  37375. return vertexData;
  37376. };
  37377. /**
  37378. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37379. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37380. * * xmin the ground minimum X coordinate, optional, default -1
  37381. * * zmin the ground minimum Z coordinate, optional, default -1
  37382. * * xmax the ground maximum X coordinate, optional, default 1
  37383. * * zmax the ground maximum Z coordinate, optional, default 1
  37384. * * 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}
  37385. * * 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}
  37386. * @returns the VertexData of the TiledGround
  37387. */
  37388. VertexData.CreateTiledGround = function (options) {
  37389. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37390. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37391. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37392. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37393. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37394. var precision = options.precision || { w: 1, h: 1 };
  37395. var indices = new Array();
  37396. var positions = new Array();
  37397. var normals = new Array();
  37398. var uvs = new Array();
  37399. var row, col, tileRow, tileCol;
  37400. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37401. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37402. precision.w = (precision.w < 1) ? 1 : precision.w;
  37403. precision.h = (precision.h < 1) ? 1 : precision.h;
  37404. var tileSize = {
  37405. 'w': (xmax - xmin) / subdivisions.w,
  37406. 'h': (zmax - zmin) / subdivisions.h
  37407. };
  37408. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37409. // Indices
  37410. var base = positions.length / 3;
  37411. var rowLength = precision.w + 1;
  37412. for (row = 0; row < precision.h; row++) {
  37413. for (col = 0; col < precision.w; col++) {
  37414. var square = [
  37415. base + col + row * rowLength,
  37416. base + (col + 1) + row * rowLength,
  37417. base + (col + 1) + (row + 1) * rowLength,
  37418. base + col + (row + 1) * rowLength
  37419. ];
  37420. indices.push(square[1]);
  37421. indices.push(square[2]);
  37422. indices.push(square[3]);
  37423. indices.push(square[0]);
  37424. indices.push(square[1]);
  37425. indices.push(square[3]);
  37426. }
  37427. }
  37428. // Position, normals and uvs
  37429. var position = BABYLON.Vector3.Zero();
  37430. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37431. for (row = 0; row <= precision.h; row++) {
  37432. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37433. for (col = 0; col <= precision.w; col++) {
  37434. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37435. position.y = 0;
  37436. positions.push(position.x, position.y, position.z);
  37437. normals.push(normal.x, normal.y, normal.z);
  37438. uvs.push(col / precision.w, row / precision.h);
  37439. }
  37440. }
  37441. }
  37442. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37443. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37444. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37445. }
  37446. }
  37447. // Result
  37448. var vertexData = new VertexData();
  37449. vertexData.indices = indices;
  37450. vertexData.positions = positions;
  37451. vertexData.normals = normals;
  37452. vertexData.uvs = uvs;
  37453. return vertexData;
  37454. };
  37455. /**
  37456. * Creates the VertexData of the Ground designed from a heightmap
  37457. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37458. * * width the width (x direction) of the ground
  37459. * * height the height (z direction) of the ground
  37460. * * subdivisions the number of subdivisions per side
  37461. * * minHeight the minimum altitude on the ground, optional, default 0
  37462. * * maxHeight the maximum altitude on the ground, optional default 1
  37463. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37464. * * buffer the array holding the image color data
  37465. * * bufferWidth the width of image
  37466. * * bufferHeight the height of image
  37467. * @returns the VertexData of the Ground designed from a heightmap
  37468. */
  37469. VertexData.CreateGroundFromHeightMap = function (options) {
  37470. var indices = [];
  37471. var positions = [];
  37472. var normals = [];
  37473. var uvs = [];
  37474. var row, col;
  37475. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37476. // Vertices
  37477. for (row = 0; row <= options.subdivisions; row++) {
  37478. for (col = 0; col <= options.subdivisions; col++) {
  37479. 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));
  37480. // Compute height
  37481. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37482. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37483. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37484. var r = options.buffer[pos] / 255.0;
  37485. var g = options.buffer[pos + 1] / 255.0;
  37486. var b = options.buffer[pos + 2] / 255.0;
  37487. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37488. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37489. // Add vertex
  37490. positions.push(position.x, position.y, position.z);
  37491. normals.push(0, 0, 0);
  37492. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37493. }
  37494. }
  37495. // Indices
  37496. for (row = 0; row < options.subdivisions; row++) {
  37497. for (col = 0; col < options.subdivisions; col++) {
  37498. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37499. indices.push(col + 1 + row * (options.subdivisions + 1));
  37500. indices.push(col + row * (options.subdivisions + 1));
  37501. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37502. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37503. indices.push(col + row * (options.subdivisions + 1));
  37504. }
  37505. }
  37506. // Normals
  37507. VertexData.ComputeNormals(positions, indices, normals);
  37508. // Result
  37509. var vertexData = new VertexData();
  37510. vertexData.indices = indices;
  37511. vertexData.positions = positions;
  37512. vertexData.normals = normals;
  37513. vertexData.uvs = uvs;
  37514. return vertexData;
  37515. };
  37516. /**
  37517. * Creates the VertexData for a Plane
  37518. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37519. * * size sets the width and height of the plane to the value of size, optional default 1
  37520. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37521. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37522. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37523. * * 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)
  37524. * * 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)
  37525. * @returns the VertexData of the box
  37526. */
  37527. VertexData.CreatePlane = function (options) {
  37528. var indices = [];
  37529. var positions = [];
  37530. var normals = [];
  37531. var uvs = [];
  37532. var width = options.width || options.size || 1;
  37533. var height = options.height || options.size || 1;
  37534. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37535. // Vertices
  37536. var halfWidth = width / 2.0;
  37537. var halfHeight = height / 2.0;
  37538. positions.push(-halfWidth, -halfHeight, 0);
  37539. normals.push(0, 0, -1.0);
  37540. uvs.push(0.0, 0.0);
  37541. positions.push(halfWidth, -halfHeight, 0);
  37542. normals.push(0, 0, -1.0);
  37543. uvs.push(1.0, 0.0);
  37544. positions.push(halfWidth, halfHeight, 0);
  37545. normals.push(0, 0, -1.0);
  37546. uvs.push(1.0, 1.0);
  37547. positions.push(-halfWidth, halfHeight, 0);
  37548. normals.push(0, 0, -1.0);
  37549. uvs.push(0.0, 1.0);
  37550. // Indices
  37551. indices.push(0);
  37552. indices.push(1);
  37553. indices.push(2);
  37554. indices.push(0);
  37555. indices.push(2);
  37556. indices.push(3);
  37557. // Sides
  37558. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37559. // Result
  37560. var vertexData = new VertexData();
  37561. vertexData.indices = indices;
  37562. vertexData.positions = positions;
  37563. vertexData.normals = normals;
  37564. vertexData.uvs = uvs;
  37565. return vertexData;
  37566. };
  37567. /**
  37568. * Creates the VertexData of the Disc or regular Polygon
  37569. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37570. * * radius the radius of the disc, optional default 0.5
  37571. * * tessellation the number of polygon sides, optional, default 64
  37572. * * 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
  37573. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37574. * * 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)
  37575. * * 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)
  37576. * @returns the VertexData of the box
  37577. */
  37578. VertexData.CreateDisc = function (options) {
  37579. var positions = new Array();
  37580. var indices = new Array();
  37581. var normals = new Array();
  37582. var uvs = new Array();
  37583. var radius = options.radius || 0.5;
  37584. var tessellation = options.tessellation || 64;
  37585. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37586. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37587. // positions and uvs
  37588. positions.push(0, 0, 0); // disc center first
  37589. uvs.push(0.5, 0.5);
  37590. var theta = Math.PI * 2 * arc;
  37591. var step = theta / tessellation;
  37592. for (var a = 0; a < theta; a += step) {
  37593. var x = Math.cos(a);
  37594. var y = Math.sin(a);
  37595. var u = (x + 1) / 2;
  37596. var v = (1 - y) / 2;
  37597. positions.push(radius * x, radius * y, 0);
  37598. uvs.push(u, v);
  37599. }
  37600. if (arc === 1) {
  37601. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37602. uvs.push(uvs[2], uvs[3]);
  37603. }
  37604. //indices
  37605. var vertexNb = positions.length / 3;
  37606. for (var i = 1; i < vertexNb - 1; i++) {
  37607. indices.push(i + 1, 0, i);
  37608. }
  37609. // result
  37610. VertexData.ComputeNormals(positions, indices, normals);
  37611. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37612. var vertexData = new VertexData();
  37613. vertexData.indices = indices;
  37614. vertexData.positions = positions;
  37615. vertexData.normals = normals;
  37616. vertexData.uvs = uvs;
  37617. return vertexData;
  37618. };
  37619. /**
  37620. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37621. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37622. * @param polygon a mesh built from polygonTriangulation.build()
  37623. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37624. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37625. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37626. * @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)
  37627. * @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)
  37628. * @returns the VertexData of the Polygon
  37629. */
  37630. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37631. var faceUV = fUV || new Array(3);
  37632. var faceColors = fColors;
  37633. var colors = [];
  37634. // default face colors and UV if undefined
  37635. for (var f = 0; f < 3; f++) {
  37636. if (faceUV[f] === undefined) {
  37637. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37638. }
  37639. if (faceColors && faceColors[f] === undefined) {
  37640. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37641. }
  37642. }
  37643. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37644. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37645. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37646. var indices = polygon.getIndices();
  37647. // set face colours and textures
  37648. var idx = 0;
  37649. var face = 0;
  37650. for (var index = 0; index < normals.length; index += 3) {
  37651. //Edge Face no. 1
  37652. if (Math.abs(normals[index + 1]) < 0.001) {
  37653. face = 1;
  37654. }
  37655. //Top Face no. 0
  37656. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37657. face = 0;
  37658. }
  37659. //Bottom Face no. 2
  37660. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37661. face = 2;
  37662. }
  37663. idx = index / 3;
  37664. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37665. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37666. if (faceColors) {
  37667. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37668. }
  37669. }
  37670. // sides
  37671. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37672. // Result
  37673. var vertexData = new VertexData();
  37674. vertexData.indices = indices;
  37675. vertexData.positions = positions;
  37676. vertexData.normals = normals;
  37677. vertexData.uvs = uvs;
  37678. if (faceColors) {
  37679. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37680. vertexData.colors = totalColors;
  37681. }
  37682. return vertexData;
  37683. };
  37684. /**
  37685. * Creates the VertexData of the IcoSphere
  37686. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37687. * * radius the radius of the IcoSphere, optional default 1
  37688. * * radiusX allows stretching in the x direction, optional, default radius
  37689. * * radiusY allows stretching in the y direction, optional, default radius
  37690. * * radiusZ allows stretching in the z direction, optional, default radius
  37691. * * flat when true creates a flat shaded mesh, optional, default true
  37692. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37693. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37694. * * 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)
  37695. * * 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)
  37696. * @returns the VertexData of the IcoSphere
  37697. */
  37698. VertexData.CreateIcoSphere = function (options) {
  37699. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37700. var radius = options.radius || 1;
  37701. var flat = (options.flat === undefined) ? true : options.flat;
  37702. var subdivisions = options.subdivisions || 4;
  37703. var radiusX = options.radiusX || radius;
  37704. var radiusY = options.radiusY || radius;
  37705. var radiusZ = options.radiusZ || radius;
  37706. var t = (1 + Math.sqrt(5)) / 2;
  37707. // 12 vertex x,y,z
  37708. var ico_vertices = [
  37709. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37710. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37711. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37712. ];
  37713. // index of 3 vertex makes a face of icopshere
  37714. var ico_indices = [
  37715. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37716. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37717. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37718. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37719. ];
  37720. // vertex for uv have aliased position, not for UV
  37721. var vertices_unalias_id = [
  37722. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37723. // vertex alias
  37724. 0,
  37725. 2,
  37726. 3,
  37727. 3,
  37728. 3,
  37729. 4,
  37730. 7,
  37731. 8,
  37732. 9,
  37733. 9,
  37734. 10,
  37735. 11 // 23: B + 12
  37736. ];
  37737. // uv as integer step (not pixels !)
  37738. var ico_vertexuv = [
  37739. 5, 1, 3, 1, 6, 4, 0, 0,
  37740. 5, 3, 4, 2, 2, 2, 4, 0,
  37741. 2, 0, 1, 1, 6, 0, 6, 2,
  37742. // vertex alias (for same vertex on different faces)
  37743. 0, 4,
  37744. 3, 3,
  37745. 4, 4,
  37746. 3, 1,
  37747. 4, 2,
  37748. 4, 4,
  37749. 0, 2,
  37750. 1, 1,
  37751. 2, 2,
  37752. 3, 3,
  37753. 1, 3,
  37754. 2, 4 // 23: B + 12
  37755. ];
  37756. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37757. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37758. // First island of uv mapping
  37759. // v = 4h 3+ 2
  37760. // v = 3h 9+ 4
  37761. // v = 2h 9+ 5 B
  37762. // v = 1h 9 1 0
  37763. // v = 0h 3 8 7 A
  37764. // u = 0 1 2 3 4 5 6 *a
  37765. // Second island of uv mapping
  37766. // v = 4h 0+ B+ 4+
  37767. // v = 3h A+ 2+
  37768. // v = 2h 7+ 6 3+
  37769. // v = 1h 8+ 3+
  37770. // v = 0h
  37771. // u = 0 1 2 3 4 5 6 *a
  37772. // Face layout on texture UV mapping
  37773. // ============
  37774. // \ 4 /\ 16 / ======
  37775. // \ / \ / /\ 11 /
  37776. // \/ 7 \/ / \ /
  37777. // ======= / 10 \/
  37778. // /\ 17 /\ =======
  37779. // / \ / \ \ 15 /\
  37780. // / 8 \/ 12 \ \ / \
  37781. // ============ \/ 6 \
  37782. // \ 18 /\ ============
  37783. // \ / \ \ 5 /\ 0 /
  37784. // \/ 13 \ \ / \ /
  37785. // ======= \/ 1 \/
  37786. // =============
  37787. // /\ 19 /\ 2 /\
  37788. // / \ / \ / \
  37789. // / 14 \/ 9 \/ 3 \
  37790. // ===================
  37791. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37792. var ustep = 138 / 1024;
  37793. var vstep = 239 / 1024;
  37794. var uoffset = 60 / 1024;
  37795. var voffset = 26 / 1024;
  37796. // Second island should have margin, not to touch the first island
  37797. // avoid any borderline artefact in pixel rounding
  37798. var island_u_offset = -40 / 1024;
  37799. var island_v_offset = +20 / 1024;
  37800. // face is either island 0 or 1 :
  37801. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37802. var island = [
  37803. 0, 0, 0, 0, 1,
  37804. 0, 0, 1, 1, 0,
  37805. 0, 0, 1, 1, 0,
  37806. 0, 1, 1, 1, 0 // 15 - 19
  37807. ];
  37808. var indices = new Array();
  37809. var positions = new Array();
  37810. var normals = new Array();
  37811. var uvs = new Array();
  37812. var current_indice = 0;
  37813. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37814. var face_vertex_pos = new Array(3);
  37815. var face_vertex_uv = new Array(3);
  37816. var v012;
  37817. for (v012 = 0; v012 < 3; v012++) {
  37818. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37819. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37820. }
  37821. // create all with normals
  37822. for (var face = 0; face < 20; face++) {
  37823. // 3 vertex per face
  37824. for (v012 = 0; v012 < 3; v012++) {
  37825. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37826. var v_id = ico_indices[3 * face + v012];
  37827. // vertex have 3D position (x,y,z)
  37828. 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]);
  37829. // Normalize to get normal, then scale to radius
  37830. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37831. // uv Coordinates from vertex ID
  37832. 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);
  37833. }
  37834. // Subdivide the face (interpolate pos, norm, uv)
  37835. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37836. // - norm is linear interpolation of vertex corner normal
  37837. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37838. // - uv is linear interpolation
  37839. //
  37840. // Topology is as below for sub-divide by 2
  37841. // vertex shown as v0,v1,v2
  37842. // interp index is i1 to progress in range [v0,v1[
  37843. // interp index is i2 to progress in range [v0,v2[
  37844. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37845. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37846. //
  37847. //
  37848. // i2 v2
  37849. // ^ ^
  37850. // / / \
  37851. // / / \
  37852. // / / \
  37853. // / / (0,1) \
  37854. // / #---------\
  37855. // / / \ (0,0)'/ \
  37856. // / / \ / \
  37857. // / / \ / \
  37858. // / / (0,0) \ / (1,0) \
  37859. // / #---------#---------\
  37860. // v0 v1
  37861. //
  37862. // --------------------> i1
  37863. //
  37864. // interp of (i1,i2):
  37865. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37866. // along i1 : lerp(x0,x1, i1/(S-i2))
  37867. //
  37868. // centroid of triangle is needed to get help normal computation
  37869. // (c1,c2) are used for centroid location
  37870. var interp_vertex = function (i1, i2, c1, c2) {
  37871. // vertex is interpolated from
  37872. // - face_vertex_pos[0..2]
  37873. // - face_vertex_uv[0..2]
  37874. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37875. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37876. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37877. pos_interp.normalize();
  37878. var vertex_normal;
  37879. if (flat) {
  37880. // in flat mode, recalculate normal as face centroid normal
  37881. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37882. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37883. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37884. }
  37885. else {
  37886. // in smooth mode, recalculate normal from each single vertex position
  37887. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37888. }
  37889. // Vertex normal need correction due to X,Y,Z radius scaling
  37890. vertex_normal.x /= radiusX;
  37891. vertex_normal.y /= radiusY;
  37892. vertex_normal.z /= radiusZ;
  37893. vertex_normal.normalize();
  37894. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37895. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37896. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37897. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37898. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37899. uvs.push(uv_interp.x, uv_interp.y);
  37900. // push each vertex has member of a face
  37901. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37902. indices.push(current_indice);
  37903. current_indice++;
  37904. };
  37905. for (var i2 = 0; i2 < subdivisions; i2++) {
  37906. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37907. // face : (i1,i2) for /\ :
  37908. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37909. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37910. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37911. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37912. if (i1 + i2 + 1 < subdivisions) {
  37913. // face : (i1,i2)' for \/ :
  37914. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37915. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37916. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37917. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37918. }
  37919. }
  37920. }
  37921. }
  37922. // Sides
  37923. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37924. // Result
  37925. var vertexData = new VertexData();
  37926. vertexData.indices = indices;
  37927. vertexData.positions = positions;
  37928. vertexData.normals = normals;
  37929. vertexData.uvs = uvs;
  37930. return vertexData;
  37931. };
  37932. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37933. /**
  37934. * Creates the VertexData for a Polyhedron
  37935. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37936. * * type provided types are:
  37937. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37938. * * 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)
  37939. * * size the size of the IcoSphere, optional default 1
  37940. * * sizeX allows stretching in the x direction, optional, default size
  37941. * * sizeY allows stretching in the y direction, optional, default size
  37942. * * sizeZ allows stretching in the z direction, optional, default size
  37943. * * 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
  37944. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37945. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37946. * * flat when true creates a flat shaded mesh, optional, default true
  37947. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37948. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37949. * * 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)
  37950. * * 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)
  37951. * @returns the VertexData of the Polyhedron
  37952. */
  37953. VertexData.CreatePolyhedron = function (options) {
  37954. // provided polyhedron types :
  37955. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37956. // 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)
  37957. var polyhedra = [];
  37958. 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]] };
  37959. 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]] };
  37960. polyhedra[2] = {
  37961. 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]],
  37962. 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]]
  37963. };
  37964. polyhedra[3] = {
  37965. 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]],
  37966. 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]]
  37967. };
  37968. polyhedra[4] = {
  37969. 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]],
  37970. 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]]
  37971. };
  37972. 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]] };
  37973. 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]] };
  37974. 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]] };
  37975. 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]] };
  37976. 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]] };
  37977. 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]] };
  37978. 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]] };
  37979. 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]] };
  37980. 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]] };
  37981. polyhedra[14] = {
  37982. 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]],
  37983. 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]]
  37984. };
  37985. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37986. var size = options.size;
  37987. var sizeX = options.sizeX || size || 1;
  37988. var sizeY = options.sizeY || size || 1;
  37989. var sizeZ = options.sizeZ || size || 1;
  37990. var data = options.custom || polyhedra[type];
  37991. var nbfaces = data.face.length;
  37992. var faceUV = options.faceUV || new Array(nbfaces);
  37993. var faceColors = options.faceColors;
  37994. var flat = (options.flat === undefined) ? true : options.flat;
  37995. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37996. var positions = new Array();
  37997. var indices = new Array();
  37998. var normals = new Array();
  37999. var uvs = new Array();
  38000. var colors = new Array();
  38001. var index = 0;
  38002. var faceIdx = 0; // face cursor in the array "indexes"
  38003. var indexes = new Array();
  38004. var i = 0;
  38005. var f = 0;
  38006. var u, v, ang, x, y, tmp;
  38007. // default face colors and UV if undefined
  38008. if (flat) {
  38009. for (f = 0; f < nbfaces; f++) {
  38010. if (faceColors && faceColors[f] === undefined) {
  38011. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38012. }
  38013. if (faceUV && faceUV[f] === undefined) {
  38014. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38015. }
  38016. }
  38017. }
  38018. if (!flat) {
  38019. for (i = 0; i < data.vertex.length; i++) {
  38020. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38021. uvs.push(0, 0);
  38022. }
  38023. for (f = 0; f < nbfaces; f++) {
  38024. for (i = 0; i < data.face[f].length - 2; i++) {
  38025. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38026. }
  38027. }
  38028. }
  38029. else {
  38030. for (f = 0; f < nbfaces; f++) {
  38031. var fl = data.face[f].length; // number of vertices of the current face
  38032. ang = 2 * Math.PI / fl;
  38033. x = 0.5 * Math.tan(ang / 2);
  38034. y = 0.5;
  38035. // positions, uvs, colors
  38036. for (i = 0; i < fl; i++) {
  38037. // positions
  38038. 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);
  38039. indexes.push(index);
  38040. index++;
  38041. // uvs
  38042. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38043. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38044. uvs.push(u, v);
  38045. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38046. y = x * Math.sin(ang) + y * Math.cos(ang);
  38047. x = tmp;
  38048. // colors
  38049. if (faceColors) {
  38050. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38051. }
  38052. }
  38053. // indices from indexes
  38054. for (i = 0; i < fl - 2; i++) {
  38055. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38056. }
  38057. faceIdx += fl;
  38058. }
  38059. }
  38060. VertexData.ComputeNormals(positions, indices, normals);
  38061. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38062. var vertexData = new VertexData();
  38063. vertexData.positions = positions;
  38064. vertexData.indices = indices;
  38065. vertexData.normals = normals;
  38066. vertexData.uvs = uvs;
  38067. if (faceColors && flat) {
  38068. vertexData.colors = colors;
  38069. }
  38070. return vertexData;
  38071. };
  38072. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38073. /**
  38074. * Creates the VertexData for a TorusKnot
  38075. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38076. * * radius the radius of the torus knot, optional, default 2
  38077. * * tube the thickness of the tube, optional, default 0.5
  38078. * * radialSegments the number of sides on each tube segments, optional, default 32
  38079. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38080. * * p the number of windings around the z axis, optional, default 2
  38081. * * q the number of windings around the x axis, optional, default 3
  38082. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38083. * * 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)
  38084. * * 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)
  38085. * @returns the VertexData of the Torus Knot
  38086. */
  38087. VertexData.CreateTorusKnot = function (options) {
  38088. var indices = new Array();
  38089. var positions = new Array();
  38090. var normals = new Array();
  38091. var uvs = new Array();
  38092. var radius = options.radius || 2;
  38093. var tube = options.tube || 0.5;
  38094. var radialSegments = options.radialSegments || 32;
  38095. var tubularSegments = options.tubularSegments || 32;
  38096. var p = options.p || 2;
  38097. var q = options.q || 3;
  38098. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38099. // Helper
  38100. var getPos = function (angle) {
  38101. var cu = Math.cos(angle);
  38102. var su = Math.sin(angle);
  38103. var quOverP = q / p * angle;
  38104. var cs = Math.cos(quOverP);
  38105. var tx = radius * (2 + cs) * 0.5 * cu;
  38106. var ty = radius * (2 + cs) * su * 0.5;
  38107. var tz = radius * Math.sin(quOverP) * 0.5;
  38108. return new BABYLON.Vector3(tx, ty, tz);
  38109. };
  38110. // Vertices
  38111. var i;
  38112. var j;
  38113. for (i = 0; i <= radialSegments; i++) {
  38114. var modI = i % radialSegments;
  38115. var u = modI / radialSegments * 2 * p * Math.PI;
  38116. var p1 = getPos(u);
  38117. var p2 = getPos(u + 0.01);
  38118. var tang = p2.subtract(p1);
  38119. var n = p2.add(p1);
  38120. var bitan = BABYLON.Vector3.Cross(tang, n);
  38121. n = BABYLON.Vector3.Cross(bitan, tang);
  38122. bitan.normalize();
  38123. n.normalize();
  38124. for (j = 0; j < tubularSegments; j++) {
  38125. var modJ = j % tubularSegments;
  38126. var v = modJ / tubularSegments * 2 * Math.PI;
  38127. var cx = -tube * Math.cos(v);
  38128. var cy = tube * Math.sin(v);
  38129. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38130. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38131. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38132. uvs.push(i / radialSegments);
  38133. uvs.push(j / tubularSegments);
  38134. }
  38135. }
  38136. for (i = 0; i < radialSegments; i++) {
  38137. for (j = 0; j < tubularSegments; j++) {
  38138. var jNext = (j + 1) % tubularSegments;
  38139. var a = i * tubularSegments + j;
  38140. var b = (i + 1) * tubularSegments + j;
  38141. var c = (i + 1) * tubularSegments + jNext;
  38142. var d = i * tubularSegments + jNext;
  38143. indices.push(d);
  38144. indices.push(b);
  38145. indices.push(a);
  38146. indices.push(d);
  38147. indices.push(c);
  38148. indices.push(b);
  38149. }
  38150. }
  38151. // Normals
  38152. VertexData.ComputeNormals(positions, indices, normals);
  38153. // Sides
  38154. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38155. // Result
  38156. var vertexData = new VertexData();
  38157. vertexData.indices = indices;
  38158. vertexData.positions = positions;
  38159. vertexData.normals = normals;
  38160. vertexData.uvs = uvs;
  38161. return vertexData;
  38162. };
  38163. // Tools
  38164. /**
  38165. * Compute normals for given positions and indices
  38166. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38167. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38168. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38169. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38170. * * facetNormals : optional array of facet normals (vector3)
  38171. * * facetPositions : optional array of facet positions (vector3)
  38172. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38173. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38174. * * bInfo : optional bounding info, required for facetPartitioning computation
  38175. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38176. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38177. * * useRightHandedSystem: optional boolean to for right handed system computation
  38178. * * depthSort : optional boolean to enable the facet depth sort computation
  38179. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38180. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38181. */
  38182. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38183. // temporary scalar variables
  38184. var index = 0; // facet index
  38185. var p1p2x = 0.0; // p1p2 vector x coordinate
  38186. var p1p2y = 0.0; // p1p2 vector y coordinate
  38187. var p1p2z = 0.0; // p1p2 vector z coordinate
  38188. var p3p2x = 0.0; // p3p2 vector x coordinate
  38189. var p3p2y = 0.0; // p3p2 vector y coordinate
  38190. var p3p2z = 0.0; // p3p2 vector z coordinate
  38191. var faceNormalx = 0.0; // facet normal x coordinate
  38192. var faceNormaly = 0.0; // facet normal y coordinate
  38193. var faceNormalz = 0.0; // facet normal z coordinate
  38194. var length = 0.0; // facet normal length before normalization
  38195. var v1x = 0; // vector1 x index in the positions array
  38196. var v1y = 0; // vector1 y index in the positions array
  38197. var v1z = 0; // vector1 z index in the positions array
  38198. var v2x = 0; // vector2 x index in the positions array
  38199. var v2y = 0; // vector2 y index in the positions array
  38200. var v2z = 0; // vector2 z index in the positions array
  38201. var v3x = 0; // vector3 x index in the positions array
  38202. var v3y = 0; // vector3 y index in the positions array
  38203. var v3z = 0; // vector3 z index in the positions array
  38204. var computeFacetNormals = false;
  38205. var computeFacetPositions = false;
  38206. var computeFacetPartitioning = false;
  38207. var computeDepthSort = false;
  38208. var faceNormalSign = 1;
  38209. var ratio = 0;
  38210. var distanceTo = null;
  38211. if (options) {
  38212. computeFacetNormals = (options.facetNormals) ? true : false;
  38213. computeFacetPositions = (options.facetPositions) ? true : false;
  38214. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38215. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38216. ratio = options.ratio || 0;
  38217. computeDepthSort = (options.depthSort) ? true : false;
  38218. distanceTo = (options.distanceTo);
  38219. if (computeDepthSort) {
  38220. if (distanceTo === undefined) {
  38221. distanceTo = BABYLON.Vector3.Zero();
  38222. }
  38223. var depthSortedFacets = options.depthSortedFacets;
  38224. }
  38225. }
  38226. // facetPartitioning reinit if needed
  38227. var xSubRatio = 0;
  38228. var ySubRatio = 0;
  38229. var zSubRatio = 0;
  38230. var subSq = 0;
  38231. if (computeFacetPartitioning && options && options.bbSize) {
  38232. var ox = 0; // X partitioning index for facet position
  38233. var oy = 0; // Y partinioning index for facet position
  38234. var oz = 0; // Z partinioning index for facet position
  38235. var b1x = 0; // X partitioning index for facet v1 vertex
  38236. var b1y = 0; // Y partitioning index for facet v1 vertex
  38237. var b1z = 0; // z partitioning index for facet v1 vertex
  38238. var b2x = 0; // X partitioning index for facet v2 vertex
  38239. var b2y = 0; // Y partitioning index for facet v2 vertex
  38240. var b2z = 0; // Z partitioning index for facet v2 vertex
  38241. var b3x = 0; // X partitioning index for facet v3 vertex
  38242. var b3y = 0; // Y partitioning index for facet v3 vertex
  38243. var b3z = 0; // Z partitioning index for facet v3 vertex
  38244. var block_idx_o = 0; // facet barycenter block index
  38245. var block_idx_v1 = 0; // v1 vertex block index
  38246. var block_idx_v2 = 0; // v2 vertex block index
  38247. var block_idx_v3 = 0; // v3 vertex block index
  38248. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38249. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38250. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38251. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38252. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38253. subSq = options.subDiv.max * options.subDiv.max;
  38254. options.facetPartitioning.length = 0;
  38255. }
  38256. // reset the normals
  38257. for (index = 0; index < positions.length; index++) {
  38258. normals[index] = 0.0;
  38259. }
  38260. // Loop : 1 indice triplet = 1 facet
  38261. var nbFaces = (indices.length / 3) | 0;
  38262. for (index = 0; index < nbFaces; index++) {
  38263. // get the indexes of the coordinates of each vertex of the facet
  38264. v1x = indices[index * 3] * 3;
  38265. v1y = v1x + 1;
  38266. v1z = v1x + 2;
  38267. v2x = indices[index * 3 + 1] * 3;
  38268. v2y = v2x + 1;
  38269. v2z = v2x + 2;
  38270. v3x = indices[index * 3 + 2] * 3;
  38271. v3y = v3x + 1;
  38272. v3z = v3x + 2;
  38273. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38274. p1p2y = positions[v1y] - positions[v2y];
  38275. p1p2z = positions[v1z] - positions[v2z];
  38276. p3p2x = positions[v3x] - positions[v2x];
  38277. p3p2y = positions[v3y] - positions[v2y];
  38278. p3p2z = positions[v3z] - positions[v2z];
  38279. // compute the face normal with the cross product
  38280. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38281. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38282. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38283. // normalize this normal and store it in the array facetData
  38284. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38285. length = (length === 0) ? 1.0 : length;
  38286. faceNormalx /= length;
  38287. faceNormaly /= length;
  38288. faceNormalz /= length;
  38289. if (computeFacetNormals && options) {
  38290. options.facetNormals[index].x = faceNormalx;
  38291. options.facetNormals[index].y = faceNormaly;
  38292. options.facetNormals[index].z = faceNormalz;
  38293. }
  38294. if (computeFacetPositions && options) {
  38295. // compute and the facet barycenter coordinates in the array facetPositions
  38296. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38297. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38298. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38299. }
  38300. if (computeFacetPartitioning && options) {
  38301. // store the facet indexes in arrays in the main facetPartitioning array :
  38302. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38303. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38304. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38305. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38306. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38307. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38308. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38309. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38310. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38311. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38312. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38313. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38314. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38315. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38316. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38317. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38318. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38319. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38320. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38321. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38322. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38323. // push each facet index in each block containing the vertex
  38324. options.facetPartitioning[block_idx_v1].push(index);
  38325. if (block_idx_v2 != block_idx_v1) {
  38326. options.facetPartitioning[block_idx_v2].push(index);
  38327. }
  38328. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38329. options.facetPartitioning[block_idx_v3].push(index);
  38330. }
  38331. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38332. options.facetPartitioning[block_idx_o].push(index);
  38333. }
  38334. }
  38335. if (computeDepthSort && options && options.facetPositions) {
  38336. var dsf = depthSortedFacets[index];
  38337. dsf.ind = index * 3;
  38338. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38339. }
  38340. // compute the normals anyway
  38341. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38342. normals[v1y] += faceNormaly;
  38343. normals[v1z] += faceNormalz;
  38344. normals[v2x] += faceNormalx;
  38345. normals[v2y] += faceNormaly;
  38346. normals[v2z] += faceNormalz;
  38347. normals[v3x] += faceNormalx;
  38348. normals[v3y] += faceNormaly;
  38349. normals[v3z] += faceNormalz;
  38350. }
  38351. // last normalization of each normal
  38352. for (index = 0; index < normals.length / 3; index++) {
  38353. faceNormalx = normals[index * 3];
  38354. faceNormaly = normals[index * 3 + 1];
  38355. faceNormalz = normals[index * 3 + 2];
  38356. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38357. length = (length === 0) ? 1.0 : length;
  38358. faceNormalx /= length;
  38359. faceNormaly /= length;
  38360. faceNormalz /= length;
  38361. normals[index * 3] = faceNormalx;
  38362. normals[index * 3 + 1] = faceNormaly;
  38363. normals[index * 3 + 2] = faceNormalz;
  38364. }
  38365. };
  38366. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38367. var li = indices.length;
  38368. var ln = normals.length;
  38369. var i;
  38370. var n;
  38371. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38372. switch (sideOrientation) {
  38373. case BABYLON.Mesh.FRONTSIDE:
  38374. // nothing changed
  38375. break;
  38376. case BABYLON.Mesh.BACKSIDE:
  38377. var tmp;
  38378. // indices
  38379. for (i = 0; i < li; i += 3) {
  38380. tmp = indices[i];
  38381. indices[i] = indices[i + 2];
  38382. indices[i + 2] = tmp;
  38383. }
  38384. // normals
  38385. for (n = 0; n < ln; n++) {
  38386. normals[n] = -normals[n];
  38387. }
  38388. break;
  38389. case BABYLON.Mesh.DOUBLESIDE:
  38390. // positions
  38391. var lp = positions.length;
  38392. var l = lp / 3;
  38393. for (var p = 0; p < lp; p++) {
  38394. positions[lp + p] = positions[p];
  38395. }
  38396. // indices
  38397. for (i = 0; i < li; i += 3) {
  38398. indices[i + li] = indices[i + 2] + l;
  38399. indices[i + 1 + li] = indices[i + 1] + l;
  38400. indices[i + 2 + li] = indices[i] + l;
  38401. }
  38402. // normals
  38403. for (n = 0; n < ln; n++) {
  38404. normals[ln + n] = -normals[n];
  38405. }
  38406. // uvs
  38407. var lu = uvs.length;
  38408. var u = 0;
  38409. for (u = 0; u < lu; u++) {
  38410. uvs[u + lu] = uvs[u];
  38411. }
  38412. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38413. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38414. u = 0;
  38415. for (i = 0; i < lu / 2; i++) {
  38416. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38417. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38418. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38419. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38420. u += 2;
  38421. }
  38422. break;
  38423. }
  38424. };
  38425. /**
  38426. * Applies VertexData created from the imported parameters to the geometry
  38427. * @param parsedVertexData the parsed data from an imported file
  38428. * @param geometry the geometry to apply the VertexData to
  38429. */
  38430. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38431. var vertexData = new VertexData();
  38432. // positions
  38433. var positions = parsedVertexData.positions;
  38434. if (positions) {
  38435. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38436. }
  38437. // normals
  38438. var normals = parsedVertexData.normals;
  38439. if (normals) {
  38440. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38441. }
  38442. // tangents
  38443. var tangents = parsedVertexData.tangents;
  38444. if (tangents) {
  38445. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38446. }
  38447. // uvs
  38448. var uvs = parsedVertexData.uvs;
  38449. if (uvs) {
  38450. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38451. }
  38452. // uv2s
  38453. var uv2s = parsedVertexData.uv2s;
  38454. if (uv2s) {
  38455. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38456. }
  38457. // uv3s
  38458. var uv3s = parsedVertexData.uv3s;
  38459. if (uv3s) {
  38460. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38461. }
  38462. // uv4s
  38463. var uv4s = parsedVertexData.uv4s;
  38464. if (uv4s) {
  38465. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38466. }
  38467. // uv5s
  38468. var uv5s = parsedVertexData.uv5s;
  38469. if (uv5s) {
  38470. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38471. }
  38472. // uv6s
  38473. var uv6s = parsedVertexData.uv6s;
  38474. if (uv6s) {
  38475. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38476. }
  38477. // colors
  38478. var colors = parsedVertexData.colors;
  38479. if (colors) {
  38480. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38481. }
  38482. // matricesIndices
  38483. var matricesIndices = parsedVertexData.matricesIndices;
  38484. if (matricesIndices) {
  38485. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38486. }
  38487. // matricesWeights
  38488. var matricesWeights = parsedVertexData.matricesWeights;
  38489. if (matricesWeights) {
  38490. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38491. }
  38492. // indices
  38493. var indices = parsedVertexData.indices;
  38494. if (indices) {
  38495. vertexData.indices = indices;
  38496. }
  38497. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38498. };
  38499. return VertexData;
  38500. }());
  38501. BABYLON.VertexData = VertexData;
  38502. })(BABYLON || (BABYLON = {}));
  38503. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38504. var BABYLON;
  38505. (function (BABYLON) {
  38506. /**
  38507. * Class used to store geometry data (vertex buffers + index buffer)
  38508. */
  38509. var Geometry = /** @class */ (function () {
  38510. /**
  38511. * Creates a new geometry
  38512. * @param id defines the unique ID
  38513. * @param scene defines the hosting scene
  38514. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38515. * @param updatable defines if geometry must be updatable (false by default)
  38516. * @param mesh defines the mesh that will be associated with the geometry
  38517. */
  38518. function Geometry(id, scene, vertexData, updatable, mesh) {
  38519. if (updatable === void 0) { updatable = false; }
  38520. if (mesh === void 0) { mesh = null; }
  38521. /**
  38522. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38523. */
  38524. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38525. this._totalVertices = 0;
  38526. this._isDisposed = false;
  38527. this._indexBufferIsUpdatable = false;
  38528. this.id = id;
  38529. this._engine = scene.getEngine();
  38530. this._meshes = [];
  38531. this._scene = scene;
  38532. //Init vertex buffer cache
  38533. this._vertexBuffers = {};
  38534. this._indices = [];
  38535. this._updatable = updatable;
  38536. // vertexData
  38537. if (vertexData) {
  38538. this.setAllVerticesData(vertexData, updatable);
  38539. }
  38540. else {
  38541. this._totalVertices = 0;
  38542. this._indices = [];
  38543. }
  38544. if (this._engine.getCaps().vertexArrayObject) {
  38545. this._vertexArrayObjects = {};
  38546. }
  38547. // applyToMesh
  38548. if (mesh) {
  38549. if (mesh.getClassName() === "LinesMesh") {
  38550. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38551. this._updateExtend();
  38552. }
  38553. this.applyToMesh(mesh);
  38554. mesh.computeWorldMatrix(true);
  38555. }
  38556. }
  38557. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38558. /**
  38559. * 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
  38560. */
  38561. get: function () {
  38562. return this._boundingBias;
  38563. },
  38564. /**
  38565. * 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
  38566. */
  38567. set: function (value) {
  38568. if (this._boundingBias && this._boundingBias.equals(value)) {
  38569. return;
  38570. }
  38571. this._boundingBias = value.clone();
  38572. this._updateBoundingInfo(true, null);
  38573. },
  38574. enumerable: true,
  38575. configurable: true
  38576. });
  38577. /**
  38578. * Static function used to attach a new empty geometry to a mesh
  38579. * @param mesh defines the mesh to attach the geometry to
  38580. * @returns the new {BABYLON.Geometry}
  38581. */
  38582. Geometry.CreateGeometryForMesh = function (mesh) {
  38583. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38584. geometry.applyToMesh(mesh);
  38585. return geometry;
  38586. };
  38587. Object.defineProperty(Geometry.prototype, "extend", {
  38588. /**
  38589. * Gets the current extend of the geometry
  38590. */
  38591. get: function () {
  38592. return this._extend;
  38593. },
  38594. enumerable: true,
  38595. configurable: true
  38596. });
  38597. /**
  38598. * Gets the hosting scene
  38599. * @returns the hosting {BABYLON.Scene}
  38600. */
  38601. Geometry.prototype.getScene = function () {
  38602. return this._scene;
  38603. };
  38604. /**
  38605. * Gets the hosting engine
  38606. * @returns the hosting {BABYLON.Engine}
  38607. */
  38608. Geometry.prototype.getEngine = function () {
  38609. return this._engine;
  38610. };
  38611. /**
  38612. * Defines if the geometry is ready to use
  38613. * @returns true if the geometry is ready to be used
  38614. */
  38615. Geometry.prototype.isReady = function () {
  38616. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38617. };
  38618. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38619. /**
  38620. * Gets a value indicating that the geometry should not be serialized
  38621. */
  38622. get: function () {
  38623. for (var index = 0; index < this._meshes.length; index++) {
  38624. if (!this._meshes[index].doNotSerialize) {
  38625. return false;
  38626. }
  38627. }
  38628. return true;
  38629. },
  38630. enumerable: true,
  38631. configurable: true
  38632. });
  38633. /** @hidden */
  38634. Geometry.prototype._rebuild = function () {
  38635. if (this._vertexArrayObjects) {
  38636. this._vertexArrayObjects = {};
  38637. }
  38638. // Index buffer
  38639. if (this._meshes.length !== 0 && this._indices) {
  38640. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38641. }
  38642. // Vertex buffers
  38643. for (var key in this._vertexBuffers) {
  38644. var vertexBuffer = this._vertexBuffers[key];
  38645. vertexBuffer._rebuild();
  38646. }
  38647. };
  38648. /**
  38649. * Affects all geometry data in one call
  38650. * @param vertexData defines the geometry data
  38651. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38652. */
  38653. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38654. vertexData.applyToGeometry(this, updatable);
  38655. this.notifyUpdate();
  38656. };
  38657. /**
  38658. * Set specific vertex data
  38659. * @param kind defines the data kind (Position, normal, etc...)
  38660. * @param data defines the vertex data to use
  38661. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38662. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38663. */
  38664. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38665. if (updatable === void 0) { updatable = false; }
  38666. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38667. this.setVerticesBuffer(buffer);
  38668. };
  38669. /**
  38670. * Removes a specific vertex data
  38671. * @param kind defines the data kind (Position, normal, etc...)
  38672. */
  38673. Geometry.prototype.removeVerticesData = function (kind) {
  38674. if (this._vertexBuffers[kind]) {
  38675. this._vertexBuffers[kind].dispose();
  38676. delete this._vertexBuffers[kind];
  38677. }
  38678. };
  38679. /**
  38680. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38681. * @param buffer defines the vertex buffer to use
  38682. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38683. */
  38684. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38685. if (totalVertices === void 0) { totalVertices = null; }
  38686. var kind = buffer.getKind();
  38687. if (this._vertexBuffers[kind]) {
  38688. this._vertexBuffers[kind].dispose();
  38689. }
  38690. this._vertexBuffers[kind] = buffer;
  38691. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38692. var data = buffer.getData();
  38693. if (totalVertices != null) {
  38694. this._totalVertices = totalVertices;
  38695. }
  38696. else {
  38697. if (data != null) {
  38698. this._totalVertices = data.length / (buffer.byteStride / 4);
  38699. }
  38700. }
  38701. this._updateExtend(data);
  38702. this._resetPointsArrayCache();
  38703. var meshes = this._meshes;
  38704. var numOfMeshes = meshes.length;
  38705. for (var index = 0; index < numOfMeshes; index++) {
  38706. var mesh = meshes[index];
  38707. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38708. mesh._createGlobalSubMesh(false);
  38709. mesh.computeWorldMatrix(true);
  38710. }
  38711. }
  38712. this.notifyUpdate(kind);
  38713. if (this._vertexArrayObjects) {
  38714. this._disposeVertexArrayObjects();
  38715. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38716. }
  38717. };
  38718. /**
  38719. * Update a specific vertex buffer
  38720. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38721. * It will do nothing if the buffer is not updatable
  38722. * @param kind defines the data kind (Position, normal, etc...)
  38723. * @param data defines the data to use
  38724. * @param offset defines the offset in the target buffer where to store the data
  38725. * @param useBytes set to true if the offset is in bytes
  38726. */
  38727. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38728. if (useBytes === void 0) { useBytes = false; }
  38729. var vertexBuffer = this.getVertexBuffer(kind);
  38730. if (!vertexBuffer) {
  38731. return;
  38732. }
  38733. vertexBuffer.updateDirectly(data, offset, useBytes);
  38734. this.notifyUpdate(kind);
  38735. };
  38736. /**
  38737. * Update a specific vertex buffer
  38738. * This function will create a new buffer if the current one is not updatable
  38739. * @param kind defines the data kind (Position, normal, etc...)
  38740. * @param data defines the data to use
  38741. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38742. */
  38743. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38744. if (updateExtends === void 0) { updateExtends = false; }
  38745. var vertexBuffer = this.getVertexBuffer(kind);
  38746. if (!vertexBuffer) {
  38747. return;
  38748. }
  38749. vertexBuffer.update(data);
  38750. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38751. this._updateBoundingInfo(updateExtends, data);
  38752. }
  38753. this.notifyUpdate(kind);
  38754. };
  38755. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38756. if (updateExtends) {
  38757. this._updateExtend(data);
  38758. }
  38759. var meshes = this._meshes;
  38760. var numOfMeshes = meshes.length;
  38761. this._resetPointsArrayCache();
  38762. for (var index = 0; index < numOfMeshes; index++) {
  38763. var mesh = meshes[index];
  38764. if (updateExtends) {
  38765. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38766. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38767. var subMesh = mesh.subMeshes[subIndex];
  38768. subMesh.refreshBoundingInfo();
  38769. }
  38770. }
  38771. }
  38772. };
  38773. /** @hidden */
  38774. Geometry.prototype._bind = function (effect, indexToBind) {
  38775. if (!effect) {
  38776. return;
  38777. }
  38778. if (indexToBind === undefined) {
  38779. indexToBind = this._indexBuffer;
  38780. }
  38781. var vbs = this.getVertexBuffers();
  38782. if (!vbs) {
  38783. return;
  38784. }
  38785. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38786. this._engine.bindBuffers(vbs, indexToBind, effect);
  38787. return;
  38788. }
  38789. // Using VAO
  38790. if (!this._vertexArrayObjects[effect.key]) {
  38791. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38792. }
  38793. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38794. };
  38795. /**
  38796. * Gets total number of vertices
  38797. * @returns the total number of vertices
  38798. */
  38799. Geometry.prototype.getTotalVertices = function () {
  38800. if (!this.isReady()) {
  38801. return 0;
  38802. }
  38803. return this._totalVertices;
  38804. };
  38805. /**
  38806. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38807. * @param kind defines the data kind (Position, normal, etc...)
  38808. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38809. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38810. * @returns a float array containing vertex data
  38811. */
  38812. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38813. var vertexBuffer = this.getVertexBuffer(kind);
  38814. if (!vertexBuffer) {
  38815. return null;
  38816. }
  38817. var data = vertexBuffer.getData();
  38818. if (!data) {
  38819. return null;
  38820. }
  38821. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38822. var count = this._totalVertices * vertexBuffer.getSize();
  38823. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38824. var copy_1 = new Array(count);
  38825. vertexBuffer.forEach(count, function (value, index) {
  38826. copy_1[index] = value;
  38827. });
  38828. return copy_1;
  38829. }
  38830. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38831. if (data instanceof Array) {
  38832. var offset = vertexBuffer.byteOffset / 4;
  38833. return BABYLON.Tools.Slice(data, offset, offset + count);
  38834. }
  38835. else if (data instanceof ArrayBuffer) {
  38836. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38837. }
  38838. else {
  38839. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38840. }
  38841. }
  38842. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38843. return BABYLON.Tools.Slice(data);
  38844. }
  38845. return data;
  38846. };
  38847. /**
  38848. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38849. * @param kind defines the data kind (Position, normal, etc...)
  38850. * @returns true if the vertex buffer with the specified kind is updatable
  38851. */
  38852. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38853. var vb = this._vertexBuffers[kind];
  38854. if (!vb) {
  38855. return false;
  38856. }
  38857. return vb.isUpdatable();
  38858. };
  38859. /**
  38860. * Gets a specific vertex buffer
  38861. * @param kind defines the data kind (Position, normal, etc...)
  38862. * @returns a {BABYLON.VertexBuffer}
  38863. */
  38864. Geometry.prototype.getVertexBuffer = function (kind) {
  38865. if (!this.isReady()) {
  38866. return null;
  38867. }
  38868. return this._vertexBuffers[kind];
  38869. };
  38870. /**
  38871. * Returns all vertex buffers
  38872. * @return an object holding all vertex buffers indexed by kind
  38873. */
  38874. Geometry.prototype.getVertexBuffers = function () {
  38875. if (!this.isReady()) {
  38876. return null;
  38877. }
  38878. return this._vertexBuffers;
  38879. };
  38880. /**
  38881. * Gets a boolean indicating if specific vertex buffer is present
  38882. * @param kind defines the data kind (Position, normal, etc...)
  38883. * @returns true if data is present
  38884. */
  38885. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38886. if (!this._vertexBuffers) {
  38887. if (this._delayInfo) {
  38888. return this._delayInfo.indexOf(kind) !== -1;
  38889. }
  38890. return false;
  38891. }
  38892. return this._vertexBuffers[kind] !== undefined;
  38893. };
  38894. /**
  38895. * Gets a list of all attached data kinds (Position, normal, etc...)
  38896. * @returns a list of string containing all kinds
  38897. */
  38898. Geometry.prototype.getVerticesDataKinds = function () {
  38899. var result = [];
  38900. var kind;
  38901. if (!this._vertexBuffers && this._delayInfo) {
  38902. for (kind in this._delayInfo) {
  38903. result.push(kind);
  38904. }
  38905. }
  38906. else {
  38907. for (kind in this._vertexBuffers) {
  38908. result.push(kind);
  38909. }
  38910. }
  38911. return result;
  38912. };
  38913. /**
  38914. * Update index buffer
  38915. * @param indices defines the indices to store in the index buffer
  38916. * @param offset defines the offset in the target buffer where to store the data
  38917. */
  38918. Geometry.prototype.updateIndices = function (indices, offset) {
  38919. if (!this._indexBuffer) {
  38920. return;
  38921. }
  38922. if (!this._indexBufferIsUpdatable) {
  38923. this.setIndices(indices, null, true);
  38924. }
  38925. else {
  38926. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38927. }
  38928. };
  38929. /**
  38930. * Creates a new index buffer
  38931. * @param indices defines the indices to store in the index buffer
  38932. * @param totalVertices defines the total number of vertices (could be null)
  38933. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38934. */
  38935. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38936. if (totalVertices === void 0) { totalVertices = null; }
  38937. if (updatable === void 0) { updatable = false; }
  38938. if (this._indexBuffer) {
  38939. this._engine._releaseBuffer(this._indexBuffer);
  38940. }
  38941. this._disposeVertexArrayObjects();
  38942. this._indices = indices;
  38943. this._indexBufferIsUpdatable = updatable;
  38944. if (this._meshes.length !== 0 && this._indices) {
  38945. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38946. }
  38947. if (totalVertices != undefined) { // including null and undefined
  38948. this._totalVertices = totalVertices;
  38949. }
  38950. var meshes = this._meshes;
  38951. var numOfMeshes = meshes.length;
  38952. for (var index = 0; index < numOfMeshes; index++) {
  38953. meshes[index]._createGlobalSubMesh(true);
  38954. }
  38955. this.notifyUpdate();
  38956. };
  38957. /**
  38958. * Return the total number of indices
  38959. * @returns the total number of indices
  38960. */
  38961. Geometry.prototype.getTotalIndices = function () {
  38962. if (!this.isReady()) {
  38963. return 0;
  38964. }
  38965. return this._indices.length;
  38966. };
  38967. /**
  38968. * Gets the index buffer array
  38969. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38970. * @returns the index buffer array
  38971. */
  38972. Geometry.prototype.getIndices = function (copyWhenShared) {
  38973. if (!this.isReady()) {
  38974. return null;
  38975. }
  38976. var orig = this._indices;
  38977. if (!copyWhenShared || this._meshes.length === 1) {
  38978. return orig;
  38979. }
  38980. else {
  38981. var len = orig.length;
  38982. var copy = [];
  38983. for (var i = 0; i < len; i++) {
  38984. copy.push(orig[i]);
  38985. }
  38986. return copy;
  38987. }
  38988. };
  38989. /**
  38990. * Gets the index buffer
  38991. * @return the index buffer
  38992. */
  38993. Geometry.prototype.getIndexBuffer = function () {
  38994. if (!this.isReady()) {
  38995. return null;
  38996. }
  38997. return this._indexBuffer;
  38998. };
  38999. /** @hidden */
  39000. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39001. if (effect === void 0) { effect = null; }
  39002. if (!effect || !this._vertexArrayObjects) {
  39003. return;
  39004. }
  39005. if (this._vertexArrayObjects[effect.key]) {
  39006. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39007. delete this._vertexArrayObjects[effect.key];
  39008. }
  39009. };
  39010. /**
  39011. * Release the associated resources for a specific mesh
  39012. * @param mesh defines the source mesh
  39013. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39014. */
  39015. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39016. var meshes = this._meshes;
  39017. var index = meshes.indexOf(mesh);
  39018. if (index === -1) {
  39019. return;
  39020. }
  39021. meshes.splice(index, 1);
  39022. mesh._geometry = null;
  39023. if (meshes.length === 0 && shouldDispose) {
  39024. this.dispose();
  39025. }
  39026. };
  39027. /**
  39028. * Apply current geometry to a given mesh
  39029. * @param mesh defines the mesh to apply geometry to
  39030. */
  39031. Geometry.prototype.applyToMesh = function (mesh) {
  39032. if (mesh._geometry === this) {
  39033. return;
  39034. }
  39035. var previousGeometry = mesh._geometry;
  39036. if (previousGeometry) {
  39037. previousGeometry.releaseForMesh(mesh);
  39038. }
  39039. var meshes = this._meshes;
  39040. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39041. mesh._geometry = this;
  39042. this._scene.pushGeometry(this);
  39043. meshes.push(mesh);
  39044. if (this.isReady()) {
  39045. this._applyToMesh(mesh);
  39046. }
  39047. else {
  39048. mesh._boundingInfo = this._boundingInfo;
  39049. }
  39050. };
  39051. Geometry.prototype._updateExtend = function (data) {
  39052. if (data === void 0) { data = null; }
  39053. if (!data) {
  39054. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39055. }
  39056. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39057. };
  39058. Geometry.prototype._applyToMesh = function (mesh) {
  39059. var numOfMeshes = this._meshes.length;
  39060. // vertexBuffers
  39061. for (var kind in this._vertexBuffers) {
  39062. if (numOfMeshes === 1) {
  39063. this._vertexBuffers[kind].create();
  39064. }
  39065. var buffer = this._vertexBuffers[kind].getBuffer();
  39066. if (buffer)
  39067. buffer.references = numOfMeshes;
  39068. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39069. if (!this._extend) {
  39070. this._updateExtend();
  39071. }
  39072. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39073. mesh._createGlobalSubMesh(false);
  39074. //bounding info was just created again, world matrix should be applied again.
  39075. mesh._updateBoundingInfo();
  39076. }
  39077. }
  39078. // indexBuffer
  39079. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39080. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39081. }
  39082. if (this._indexBuffer) {
  39083. this._indexBuffer.references = numOfMeshes;
  39084. }
  39085. };
  39086. Geometry.prototype.notifyUpdate = function (kind) {
  39087. if (this.onGeometryUpdated) {
  39088. this.onGeometryUpdated(this, kind);
  39089. }
  39090. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39091. var mesh = _a[_i];
  39092. mesh._markSubMeshesAsAttributesDirty();
  39093. }
  39094. };
  39095. /**
  39096. * Load the geometry if it was flagged as delay loaded
  39097. * @param scene defines the hosting scene
  39098. * @param onLoaded defines a callback called when the geometry is loaded
  39099. */
  39100. Geometry.prototype.load = function (scene, onLoaded) {
  39101. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39102. return;
  39103. }
  39104. if (this.isReady()) {
  39105. if (onLoaded) {
  39106. onLoaded();
  39107. }
  39108. return;
  39109. }
  39110. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39111. this._queueLoad(scene, onLoaded);
  39112. };
  39113. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39114. var _this = this;
  39115. if (!this.delayLoadingFile) {
  39116. return;
  39117. }
  39118. scene._addPendingData(this);
  39119. scene._loadFile(this.delayLoadingFile, function (data) {
  39120. if (!_this._delayLoadingFunction) {
  39121. return;
  39122. }
  39123. _this._delayLoadingFunction(JSON.parse(data), _this);
  39124. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39125. _this._delayInfo = [];
  39126. scene._removePendingData(_this);
  39127. var meshes = _this._meshes;
  39128. var numOfMeshes = meshes.length;
  39129. for (var index = 0; index < numOfMeshes; index++) {
  39130. _this._applyToMesh(meshes[index]);
  39131. }
  39132. if (onLoaded) {
  39133. onLoaded();
  39134. }
  39135. }, undefined, true);
  39136. };
  39137. /**
  39138. * Invert the geometry to move from a right handed system to a left handed one.
  39139. */
  39140. Geometry.prototype.toLeftHanded = function () {
  39141. // Flip faces
  39142. var tIndices = this.getIndices(false);
  39143. if (tIndices != null && tIndices.length > 0) {
  39144. for (var i = 0; i < tIndices.length; i += 3) {
  39145. var tTemp = tIndices[i + 0];
  39146. tIndices[i + 0] = tIndices[i + 2];
  39147. tIndices[i + 2] = tTemp;
  39148. }
  39149. this.setIndices(tIndices);
  39150. }
  39151. // Negate position.z
  39152. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39153. if (tPositions != null && tPositions.length > 0) {
  39154. for (var i = 0; i < tPositions.length; i += 3) {
  39155. tPositions[i + 2] = -tPositions[i + 2];
  39156. }
  39157. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39158. }
  39159. // Negate normal.z
  39160. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39161. if (tNormals != null && tNormals.length > 0) {
  39162. for (var i = 0; i < tNormals.length; i += 3) {
  39163. tNormals[i + 2] = -tNormals[i + 2];
  39164. }
  39165. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39166. }
  39167. };
  39168. // Cache
  39169. /** @hidden */
  39170. Geometry.prototype._resetPointsArrayCache = function () {
  39171. this._positions = null;
  39172. };
  39173. /** @hidden */
  39174. Geometry.prototype._generatePointsArray = function () {
  39175. if (this._positions)
  39176. return true;
  39177. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39178. if (!data || data.length === 0) {
  39179. return false;
  39180. }
  39181. this._positions = [];
  39182. for (var index = 0; index < data.length; index += 3) {
  39183. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39184. }
  39185. return true;
  39186. };
  39187. /**
  39188. * Gets a value indicating if the geometry is disposed
  39189. * @returns true if the geometry was disposed
  39190. */
  39191. Geometry.prototype.isDisposed = function () {
  39192. return this._isDisposed;
  39193. };
  39194. Geometry.prototype._disposeVertexArrayObjects = function () {
  39195. if (this._vertexArrayObjects) {
  39196. for (var kind in this._vertexArrayObjects) {
  39197. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39198. }
  39199. this._vertexArrayObjects = {};
  39200. }
  39201. };
  39202. /**
  39203. * Free all associated resources
  39204. */
  39205. Geometry.prototype.dispose = function () {
  39206. var meshes = this._meshes;
  39207. var numOfMeshes = meshes.length;
  39208. var index;
  39209. for (index = 0; index < numOfMeshes; index++) {
  39210. this.releaseForMesh(meshes[index]);
  39211. }
  39212. this._meshes = [];
  39213. this._disposeVertexArrayObjects();
  39214. for (var kind in this._vertexBuffers) {
  39215. this._vertexBuffers[kind].dispose();
  39216. }
  39217. this._vertexBuffers = {};
  39218. this._totalVertices = 0;
  39219. if (this._indexBuffer) {
  39220. this._engine._releaseBuffer(this._indexBuffer);
  39221. }
  39222. this._indexBuffer = null;
  39223. this._indices = [];
  39224. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39225. this.delayLoadingFile = null;
  39226. this._delayLoadingFunction = null;
  39227. this._delayInfo = [];
  39228. this._boundingInfo = null;
  39229. this._scene.removeGeometry(this);
  39230. this._isDisposed = true;
  39231. };
  39232. /**
  39233. * Clone the current geometry into a new geometry
  39234. * @param id defines the unique ID of the new geometry
  39235. * @returns a new geometry object
  39236. */
  39237. Geometry.prototype.copy = function (id) {
  39238. var vertexData = new BABYLON.VertexData();
  39239. vertexData.indices = [];
  39240. var indices = this.getIndices();
  39241. if (indices) {
  39242. for (var index = 0; index < indices.length; index++) {
  39243. vertexData.indices.push(indices[index]);
  39244. }
  39245. }
  39246. var updatable = false;
  39247. var stopChecking = false;
  39248. var kind;
  39249. for (kind in this._vertexBuffers) {
  39250. // using slice() to make a copy of the array and not just reference it
  39251. var data = this.getVerticesData(kind);
  39252. if (data instanceof Float32Array) {
  39253. vertexData.set(new Float32Array(data), kind);
  39254. }
  39255. else {
  39256. vertexData.set(data.slice(0), kind);
  39257. }
  39258. if (!stopChecking) {
  39259. var vb = this.getVertexBuffer(kind);
  39260. if (vb) {
  39261. updatable = vb.isUpdatable();
  39262. stopChecking = !updatable;
  39263. }
  39264. }
  39265. }
  39266. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39267. geometry.delayLoadState = this.delayLoadState;
  39268. geometry.delayLoadingFile = this.delayLoadingFile;
  39269. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39270. for (kind in this._delayInfo) {
  39271. geometry._delayInfo = geometry._delayInfo || [];
  39272. geometry._delayInfo.push(kind);
  39273. }
  39274. // Bounding info
  39275. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39276. return geometry;
  39277. };
  39278. /**
  39279. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39280. * @return a JSON representation of the current geometry data (without the vertices data)
  39281. */
  39282. Geometry.prototype.serialize = function () {
  39283. var serializationObject = {};
  39284. serializationObject.id = this.id;
  39285. serializationObject.updatable = this._updatable;
  39286. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39287. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39288. }
  39289. return serializationObject;
  39290. };
  39291. Geometry.prototype.toNumberArray = function (origin) {
  39292. if (Array.isArray(origin)) {
  39293. return origin;
  39294. }
  39295. else {
  39296. return Array.prototype.slice.call(origin);
  39297. }
  39298. };
  39299. /**
  39300. * Serialize all vertices data into a JSON oject
  39301. * @returns a JSON representation of the current geometry data
  39302. */
  39303. Geometry.prototype.serializeVerticeData = function () {
  39304. var serializationObject = this.serialize();
  39305. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39306. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39307. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39308. serializationObject.positions._updatable = true;
  39309. }
  39310. }
  39311. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39312. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39313. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39314. serializationObject.normals._updatable = true;
  39315. }
  39316. }
  39317. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39318. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39319. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39320. serializationObject.tangets._updatable = true;
  39321. }
  39322. }
  39323. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39324. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39325. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39326. serializationObject.uvs._updatable = true;
  39327. }
  39328. }
  39329. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39330. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39331. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39332. serializationObject.uv2s._updatable = true;
  39333. }
  39334. }
  39335. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39336. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39337. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39338. serializationObject.uv3s._updatable = true;
  39339. }
  39340. }
  39341. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39342. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39343. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39344. serializationObject.uv4s._updatable = true;
  39345. }
  39346. }
  39347. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39348. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39349. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39350. serializationObject.uv5s._updatable = true;
  39351. }
  39352. }
  39353. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39354. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39355. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39356. serializationObject.uv6s._updatable = true;
  39357. }
  39358. }
  39359. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39360. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39361. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39362. serializationObject.colors._updatable = true;
  39363. }
  39364. }
  39365. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39366. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39367. serializationObject.matricesIndices._isExpanded = true;
  39368. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39369. serializationObject.matricesIndices._updatable = true;
  39370. }
  39371. }
  39372. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39373. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39374. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39375. serializationObject.matricesWeights._updatable = true;
  39376. }
  39377. }
  39378. serializationObject.indices = this.toNumberArray(this.getIndices());
  39379. return serializationObject;
  39380. };
  39381. // Statics
  39382. /**
  39383. * Extracts a clone of a mesh geometry
  39384. * @param mesh defines the source mesh
  39385. * @param id defines the unique ID of the new geometry object
  39386. * @returns the new geometry object
  39387. */
  39388. Geometry.ExtractFromMesh = function (mesh, id) {
  39389. var geometry = mesh._geometry;
  39390. if (!geometry) {
  39391. return null;
  39392. }
  39393. return geometry.copy(id);
  39394. };
  39395. /**
  39396. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39397. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39398. * Be aware Math.random() could cause collisions, but:
  39399. * "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"
  39400. * @returns a string containing a new GUID
  39401. */
  39402. Geometry.RandomId = function () {
  39403. return BABYLON.Tools.RandomId();
  39404. };
  39405. /** @hidden */
  39406. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39407. var scene = mesh.getScene();
  39408. // Geometry
  39409. var geometryId = parsedGeometry.geometryId;
  39410. if (geometryId) {
  39411. var geometry = scene.getGeometryByID(geometryId);
  39412. if (geometry) {
  39413. geometry.applyToMesh(mesh);
  39414. }
  39415. }
  39416. else if (parsedGeometry instanceof ArrayBuffer) {
  39417. var binaryInfo = mesh._binaryInfo;
  39418. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39419. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39420. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39421. }
  39422. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39423. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39424. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39425. }
  39426. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39427. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39428. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39429. }
  39430. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39431. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39432. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39433. }
  39434. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39435. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39436. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39437. }
  39438. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39439. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39440. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39441. }
  39442. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39443. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39444. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39445. }
  39446. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39447. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39448. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39449. }
  39450. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39451. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39452. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39453. }
  39454. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39455. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39456. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39457. }
  39458. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39459. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39460. var floatIndices = [];
  39461. for (var i = 0; i < matricesIndicesData.length; i++) {
  39462. var index = matricesIndicesData[i];
  39463. floatIndices.push(index & 0x000000FF);
  39464. floatIndices.push((index & 0x0000FF00) >> 8);
  39465. floatIndices.push((index & 0x00FF0000) >> 16);
  39466. floatIndices.push(index >> 24);
  39467. }
  39468. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39469. }
  39470. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39471. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39472. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39473. }
  39474. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39475. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39476. mesh.setIndices(indicesData, null);
  39477. }
  39478. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39479. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39480. mesh.subMeshes = [];
  39481. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39482. var materialIndex = subMeshesData[(i * 5) + 0];
  39483. var verticesStart = subMeshesData[(i * 5) + 1];
  39484. var verticesCount = subMeshesData[(i * 5) + 2];
  39485. var indexStart = subMeshesData[(i * 5) + 3];
  39486. var indexCount = subMeshesData[(i * 5) + 4];
  39487. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39488. }
  39489. }
  39490. }
  39491. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39492. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39493. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39494. if (parsedGeometry.tangents) {
  39495. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39496. }
  39497. if (parsedGeometry.uvs) {
  39498. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39499. }
  39500. if (parsedGeometry.uvs2) {
  39501. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39502. }
  39503. if (parsedGeometry.uvs3) {
  39504. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39505. }
  39506. if (parsedGeometry.uvs4) {
  39507. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39508. }
  39509. if (parsedGeometry.uvs5) {
  39510. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39511. }
  39512. if (parsedGeometry.uvs6) {
  39513. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39514. }
  39515. if (parsedGeometry.colors) {
  39516. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39517. }
  39518. if (parsedGeometry.matricesIndices) {
  39519. if (!parsedGeometry.matricesIndices._isExpanded) {
  39520. var floatIndices = [];
  39521. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39522. var matricesIndex = parsedGeometry.matricesIndices[i];
  39523. floatIndices.push(matricesIndex & 0x000000FF);
  39524. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39525. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39526. floatIndices.push(matricesIndex >> 24);
  39527. }
  39528. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39529. }
  39530. else {
  39531. delete parsedGeometry.matricesIndices._isExpanded;
  39532. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39533. }
  39534. }
  39535. if (parsedGeometry.matricesIndicesExtra) {
  39536. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39537. var floatIndices = [];
  39538. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39539. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39540. floatIndices.push(matricesIndex & 0x000000FF);
  39541. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39542. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39543. floatIndices.push(matricesIndex >> 24);
  39544. }
  39545. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39546. }
  39547. else {
  39548. delete parsedGeometry.matricesIndices._isExpanded;
  39549. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39550. }
  39551. }
  39552. if (parsedGeometry.matricesWeights) {
  39553. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39554. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39555. }
  39556. if (parsedGeometry.matricesWeightsExtra) {
  39557. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39558. }
  39559. mesh.setIndices(parsedGeometry.indices, null);
  39560. }
  39561. // SubMeshes
  39562. if (parsedGeometry.subMeshes) {
  39563. mesh.subMeshes = [];
  39564. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39565. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39566. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39567. }
  39568. }
  39569. // Flat shading
  39570. if (mesh._shouldGenerateFlatShading) {
  39571. mesh.convertToFlatShadedMesh();
  39572. delete mesh._shouldGenerateFlatShading;
  39573. }
  39574. // Update
  39575. mesh.computeWorldMatrix(true);
  39576. // Octree
  39577. var sceneOctree = scene.selectionOctree;
  39578. if (sceneOctree !== undefined && sceneOctree !== null) {
  39579. sceneOctree.addMesh(mesh);
  39580. }
  39581. };
  39582. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39583. var epsilon = 1e-3;
  39584. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39585. return;
  39586. }
  39587. var noInfluenceBoneIndex = 0.0;
  39588. if (parsedGeometry.skeletonId > -1) {
  39589. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39590. if (!skeleton) {
  39591. return;
  39592. }
  39593. noInfluenceBoneIndex = skeleton.bones.length;
  39594. }
  39595. else {
  39596. return;
  39597. }
  39598. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39599. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39600. var matricesWeights = parsedGeometry.matricesWeights;
  39601. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39602. var influencers = parsedGeometry.numBoneInfluencer;
  39603. var size = matricesWeights.length;
  39604. for (var i = 0; i < size; i += 4) {
  39605. var weight = 0.0;
  39606. var firstZeroWeight = -1;
  39607. for (var j = 0; j < 4; j++) {
  39608. var w = matricesWeights[i + j];
  39609. weight += w;
  39610. if (w < epsilon && firstZeroWeight < 0) {
  39611. firstZeroWeight = j;
  39612. }
  39613. }
  39614. if (matricesWeightsExtra) {
  39615. for (var j = 0; j < 4; j++) {
  39616. var w = matricesWeightsExtra[i + j];
  39617. weight += w;
  39618. if (w < epsilon && firstZeroWeight < 0) {
  39619. firstZeroWeight = j + 4;
  39620. }
  39621. }
  39622. }
  39623. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39624. firstZeroWeight = influencers - 1;
  39625. }
  39626. if (weight > epsilon) {
  39627. var mweight = 1.0 / weight;
  39628. for (var j = 0; j < 4; j++) {
  39629. matricesWeights[i + j] *= mweight;
  39630. }
  39631. if (matricesWeightsExtra) {
  39632. for (var j = 0; j < 4; j++) {
  39633. matricesWeightsExtra[i + j] *= mweight;
  39634. }
  39635. }
  39636. }
  39637. else {
  39638. if (firstZeroWeight >= 4) {
  39639. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39640. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39641. }
  39642. else {
  39643. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39644. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39645. }
  39646. }
  39647. }
  39648. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39649. if (parsedGeometry.matricesWeightsExtra) {
  39650. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39651. }
  39652. };
  39653. /**
  39654. * Create a new geometry from persisted data (Using .babylon file format)
  39655. * @param parsedVertexData defines the persisted data
  39656. * @param scene defines the hosting scene
  39657. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39658. * @returns the new geometry object
  39659. */
  39660. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39661. if (scene.getGeometryByID(parsedVertexData.id)) {
  39662. return null; // null since geometry could be something else than a box...
  39663. }
  39664. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39665. if (BABYLON.Tags) {
  39666. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39667. }
  39668. if (parsedVertexData.delayLoadingFile) {
  39669. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39670. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39671. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39672. geometry._delayInfo = [];
  39673. if (parsedVertexData.hasUVs) {
  39674. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39675. }
  39676. if (parsedVertexData.hasUVs2) {
  39677. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39678. }
  39679. if (parsedVertexData.hasUVs3) {
  39680. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39681. }
  39682. if (parsedVertexData.hasUVs4) {
  39683. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39684. }
  39685. if (parsedVertexData.hasUVs5) {
  39686. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39687. }
  39688. if (parsedVertexData.hasUVs6) {
  39689. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39690. }
  39691. if (parsedVertexData.hasColors) {
  39692. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39693. }
  39694. if (parsedVertexData.hasMatricesIndices) {
  39695. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39696. }
  39697. if (parsedVertexData.hasMatricesWeights) {
  39698. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39699. }
  39700. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39701. }
  39702. else {
  39703. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39704. }
  39705. scene.pushGeometry(geometry, true);
  39706. return geometry;
  39707. };
  39708. return Geometry;
  39709. }());
  39710. BABYLON.Geometry = Geometry;
  39711. // Primitives
  39712. /// Abstract class
  39713. /**
  39714. * Abstract class used to provide common services for all typed geometries
  39715. * @hidden
  39716. */
  39717. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39718. __extends(_PrimitiveGeometry, _super);
  39719. /**
  39720. * Creates a new typed geometry
  39721. * @param id defines the unique ID of the geometry
  39722. * @param scene defines the hosting scene
  39723. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39724. * @param mesh defines the hosting mesh (can be null)
  39725. */
  39726. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39727. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39728. if (mesh === void 0) { mesh = null; }
  39729. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39730. _this._canBeRegenerated = _canBeRegenerated;
  39731. _this._beingRegenerated = true;
  39732. _this.regenerate();
  39733. _this._beingRegenerated = false;
  39734. return _this;
  39735. }
  39736. /**
  39737. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39738. * @returns true if the geometry can be regenerated
  39739. */
  39740. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39741. return this._canBeRegenerated;
  39742. };
  39743. /**
  39744. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39745. */
  39746. _PrimitiveGeometry.prototype.regenerate = function () {
  39747. if (!this._canBeRegenerated) {
  39748. return;
  39749. }
  39750. this._beingRegenerated = true;
  39751. this.setAllVerticesData(this._regenerateVertexData(), false);
  39752. this._beingRegenerated = false;
  39753. };
  39754. /**
  39755. * Clone the geometry
  39756. * @param id defines the unique ID of the new geometry
  39757. * @returns the new geometry
  39758. */
  39759. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39760. return _super.prototype.copy.call(this, id);
  39761. };
  39762. // overrides
  39763. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39764. if (!this._beingRegenerated) {
  39765. return;
  39766. }
  39767. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39768. };
  39769. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39770. if (!this._beingRegenerated) {
  39771. return;
  39772. }
  39773. _super.prototype.setVerticesData.call(this, kind, data, false);
  39774. };
  39775. // to override
  39776. /** @hidden */
  39777. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39778. throw new Error("Abstract method");
  39779. };
  39780. _PrimitiveGeometry.prototype.copy = function (id) {
  39781. throw new Error("Must be overriden in sub-classes.");
  39782. };
  39783. _PrimitiveGeometry.prototype.serialize = function () {
  39784. var serializationObject = _super.prototype.serialize.call(this);
  39785. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39786. return serializationObject;
  39787. };
  39788. return _PrimitiveGeometry;
  39789. }(Geometry));
  39790. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39791. /**
  39792. * Creates a ribbon geometry
  39793. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39794. */
  39795. var RibbonGeometry = /** @class */ (function (_super) {
  39796. __extends(RibbonGeometry, _super);
  39797. /**
  39798. * Creates a ribbon geometry
  39799. * @param id defines the unique ID of the geometry
  39800. * @param scene defines the hosting scene
  39801. * @param pathArray defines the array of paths to use
  39802. * @param closeArray defines if the last path and the first path must be joined
  39803. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39804. * @param offset defines the offset between points
  39805. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39806. * @param mesh defines the hosting mesh (can be null)
  39807. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39808. */
  39809. function RibbonGeometry(id, scene,
  39810. /**
  39811. * Defines the array of paths to use
  39812. */
  39813. pathArray,
  39814. /**
  39815. * Defines if the last and first points of each path in your pathArray must be joined
  39816. */
  39817. closeArray,
  39818. /**
  39819. * Defines if the last and first points of each path in your pathArray must be joined
  39820. */
  39821. closePath,
  39822. /**
  39823. * Defines the offset between points
  39824. */
  39825. offset, canBeRegenerated, mesh,
  39826. /**
  39827. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39828. */
  39829. side) {
  39830. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39831. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39832. _this.pathArray = pathArray;
  39833. _this.closeArray = closeArray;
  39834. _this.closePath = closePath;
  39835. _this.offset = offset;
  39836. _this.side = side;
  39837. return _this;
  39838. }
  39839. /** @hidden */
  39840. RibbonGeometry.prototype._regenerateVertexData = function () {
  39841. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39842. };
  39843. RibbonGeometry.prototype.copy = function (id) {
  39844. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39845. };
  39846. return RibbonGeometry;
  39847. }(_PrimitiveGeometry));
  39848. BABYLON.RibbonGeometry = RibbonGeometry;
  39849. /**
  39850. * Creates a box geometry
  39851. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39852. */
  39853. var BoxGeometry = /** @class */ (function (_super) {
  39854. __extends(BoxGeometry, _super);
  39855. /**
  39856. * Creates a box geometry
  39857. * @param id defines the unique ID of the geometry
  39858. * @param scene defines the hosting scene
  39859. * @param size defines the zise of the box (width, height and depth are the same)
  39860. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39861. * @param mesh defines the hosting mesh (can be null)
  39862. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39863. */
  39864. function BoxGeometry(id, scene,
  39865. /**
  39866. * Defines the zise of the box (width, height and depth are the same)
  39867. */
  39868. size, canBeRegenerated, mesh,
  39869. /**
  39870. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39871. */
  39872. side) {
  39873. if (mesh === void 0) { mesh = null; }
  39874. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39875. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39876. _this.size = size;
  39877. _this.side = side;
  39878. return _this;
  39879. }
  39880. BoxGeometry.prototype._regenerateVertexData = function () {
  39881. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39882. };
  39883. BoxGeometry.prototype.copy = function (id) {
  39884. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39885. };
  39886. BoxGeometry.prototype.serialize = function () {
  39887. var serializationObject = _super.prototype.serialize.call(this);
  39888. serializationObject.size = this.size;
  39889. return serializationObject;
  39890. };
  39891. BoxGeometry.Parse = function (parsedBox, scene) {
  39892. if (scene.getGeometryByID(parsedBox.id)) {
  39893. return null; // null since geometry could be something else than a box...
  39894. }
  39895. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39896. if (BABYLON.Tags) {
  39897. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39898. }
  39899. scene.pushGeometry(box, true);
  39900. return box;
  39901. };
  39902. return BoxGeometry;
  39903. }(_PrimitiveGeometry));
  39904. BABYLON.BoxGeometry = BoxGeometry;
  39905. /**
  39906. * Creates a sphere geometry
  39907. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39908. */
  39909. var SphereGeometry = /** @class */ (function (_super) {
  39910. __extends(SphereGeometry, _super);
  39911. /**
  39912. * Create a new sphere geometry
  39913. * @param id defines the unique ID of the geometry
  39914. * @param scene defines the hosting scene
  39915. * @param segments defines the number of segments to use to create the sphere
  39916. * @param diameter defines the diameter of the sphere
  39917. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39918. * @param mesh defines the hosting mesh (can be null)
  39919. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39920. */
  39921. function SphereGeometry(id, scene,
  39922. /**
  39923. * Defines the number of segments to use to create the sphere
  39924. */
  39925. segments,
  39926. /**
  39927. * Defines the diameter of the sphere
  39928. */
  39929. diameter, canBeRegenerated, mesh,
  39930. /**
  39931. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39932. */
  39933. side) {
  39934. if (mesh === void 0) { mesh = null; }
  39935. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39936. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39937. _this.segments = segments;
  39938. _this.diameter = diameter;
  39939. _this.side = side;
  39940. return _this;
  39941. }
  39942. SphereGeometry.prototype._regenerateVertexData = function () {
  39943. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39944. };
  39945. SphereGeometry.prototype.copy = function (id) {
  39946. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39947. };
  39948. SphereGeometry.prototype.serialize = function () {
  39949. var serializationObject = _super.prototype.serialize.call(this);
  39950. serializationObject.segments = this.segments;
  39951. serializationObject.diameter = this.diameter;
  39952. return serializationObject;
  39953. };
  39954. SphereGeometry.Parse = function (parsedSphere, scene) {
  39955. if (scene.getGeometryByID(parsedSphere.id)) {
  39956. return null; // null since geometry could be something else than a sphere...
  39957. }
  39958. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39959. if (BABYLON.Tags) {
  39960. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39961. }
  39962. scene.pushGeometry(sphere, true);
  39963. return sphere;
  39964. };
  39965. return SphereGeometry;
  39966. }(_PrimitiveGeometry));
  39967. BABYLON.SphereGeometry = SphereGeometry;
  39968. /**
  39969. * Creates a disc geometry
  39970. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39971. */
  39972. var DiscGeometry = /** @class */ (function (_super) {
  39973. __extends(DiscGeometry, _super);
  39974. /**
  39975. * Creates a new disc geometry
  39976. * @param id defines the unique ID of the geometry
  39977. * @param scene defines the hosting scene
  39978. * @param radius defines the radius of the disc
  39979. * @param tessellation defines the tesselation factor to apply to the disc
  39980. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39981. * @param mesh defines the hosting mesh (can be null)
  39982. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39983. */
  39984. function DiscGeometry(id, scene,
  39985. /**
  39986. * Defines the radius of the disc
  39987. */
  39988. radius,
  39989. /**
  39990. * Defines the tesselation factor to apply to the disc
  39991. */
  39992. tessellation, canBeRegenerated, mesh,
  39993. /**
  39994. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39995. */
  39996. side) {
  39997. if (mesh === void 0) { mesh = null; }
  39998. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39999. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40000. _this.radius = radius;
  40001. _this.tessellation = tessellation;
  40002. _this.side = side;
  40003. return _this;
  40004. }
  40005. DiscGeometry.prototype._regenerateVertexData = function () {
  40006. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40007. };
  40008. DiscGeometry.prototype.copy = function (id) {
  40009. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40010. };
  40011. return DiscGeometry;
  40012. }(_PrimitiveGeometry));
  40013. BABYLON.DiscGeometry = DiscGeometry;
  40014. /**
  40015. * Creates a new cylinder geometry
  40016. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40017. */
  40018. var CylinderGeometry = /** @class */ (function (_super) {
  40019. __extends(CylinderGeometry, _super);
  40020. /**
  40021. * Creates a new cylinder geometry
  40022. * @param id defines the unique ID of the geometry
  40023. * @param scene defines the hosting scene
  40024. * @param height defines the height of the cylinder
  40025. * @param diameterTop defines the diameter of the cylinder's top cap
  40026. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40027. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40028. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40029. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40030. * @param mesh defines the hosting mesh (can be null)
  40031. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40032. */
  40033. function CylinderGeometry(id, scene,
  40034. /**
  40035. * Defines the height of the cylinder
  40036. */
  40037. height,
  40038. /**
  40039. * Defines the diameter of the cylinder's top cap
  40040. */
  40041. diameterTop,
  40042. /**
  40043. * Defines the diameter of the cylinder's bottom cap
  40044. */
  40045. diameterBottom,
  40046. /**
  40047. * Defines the tessellation factor to apply to the cylinder
  40048. */
  40049. tessellation,
  40050. /**
  40051. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40052. */
  40053. subdivisions, canBeRegenerated, mesh,
  40054. /**
  40055. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40056. */
  40057. side) {
  40058. if (subdivisions === void 0) { subdivisions = 1; }
  40059. if (mesh === void 0) { mesh = null; }
  40060. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40061. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40062. _this.height = height;
  40063. _this.diameterTop = diameterTop;
  40064. _this.diameterBottom = diameterBottom;
  40065. _this.tessellation = tessellation;
  40066. _this.subdivisions = subdivisions;
  40067. _this.side = side;
  40068. return _this;
  40069. }
  40070. CylinderGeometry.prototype._regenerateVertexData = function () {
  40071. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40072. };
  40073. CylinderGeometry.prototype.copy = function (id) {
  40074. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40075. };
  40076. CylinderGeometry.prototype.serialize = function () {
  40077. var serializationObject = _super.prototype.serialize.call(this);
  40078. serializationObject.height = this.height;
  40079. serializationObject.diameterTop = this.diameterTop;
  40080. serializationObject.diameterBottom = this.diameterBottom;
  40081. serializationObject.tessellation = this.tessellation;
  40082. return serializationObject;
  40083. };
  40084. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40085. if (scene.getGeometryByID(parsedCylinder.id)) {
  40086. return null; // null since geometry could be something else than a cylinder...
  40087. }
  40088. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40089. if (BABYLON.Tags) {
  40090. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40091. }
  40092. scene.pushGeometry(cylinder, true);
  40093. return cylinder;
  40094. };
  40095. return CylinderGeometry;
  40096. }(_PrimitiveGeometry));
  40097. BABYLON.CylinderGeometry = CylinderGeometry;
  40098. /**
  40099. * Creates a new torus geometry
  40100. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40101. */
  40102. var TorusGeometry = /** @class */ (function (_super) {
  40103. __extends(TorusGeometry, _super);
  40104. /**
  40105. * Creates a new torus geometry
  40106. * @param id defines the unique ID of the geometry
  40107. * @param scene defines the hosting scene
  40108. * @param diameter defines the diameter of the torus
  40109. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40110. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40111. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40112. * @param mesh defines the hosting mesh (can be null)
  40113. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40114. */
  40115. function TorusGeometry(id, scene,
  40116. /**
  40117. * Defines the diameter of the torus
  40118. */
  40119. diameter,
  40120. /**
  40121. * Defines the thickness of the torus (ie. internal diameter)
  40122. */
  40123. thickness,
  40124. /**
  40125. * Defines the tesselation factor to apply to the torus
  40126. */
  40127. tessellation, canBeRegenerated, mesh,
  40128. /**
  40129. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40130. */
  40131. side) {
  40132. if (mesh === void 0) { mesh = null; }
  40133. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40134. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40135. _this.diameter = diameter;
  40136. _this.thickness = thickness;
  40137. _this.tessellation = tessellation;
  40138. _this.side = side;
  40139. return _this;
  40140. }
  40141. TorusGeometry.prototype._regenerateVertexData = function () {
  40142. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40143. };
  40144. TorusGeometry.prototype.copy = function (id) {
  40145. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40146. };
  40147. TorusGeometry.prototype.serialize = function () {
  40148. var serializationObject = _super.prototype.serialize.call(this);
  40149. serializationObject.diameter = this.diameter;
  40150. serializationObject.thickness = this.thickness;
  40151. serializationObject.tessellation = this.tessellation;
  40152. return serializationObject;
  40153. };
  40154. TorusGeometry.Parse = function (parsedTorus, scene) {
  40155. if (scene.getGeometryByID(parsedTorus.id)) {
  40156. return null; // null since geometry could be something else than a torus...
  40157. }
  40158. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40159. if (BABYLON.Tags) {
  40160. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40161. }
  40162. scene.pushGeometry(torus, true);
  40163. return torus;
  40164. };
  40165. return TorusGeometry;
  40166. }(_PrimitiveGeometry));
  40167. BABYLON.TorusGeometry = TorusGeometry;
  40168. /**
  40169. * Creates a new ground geometry
  40170. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40171. */
  40172. var GroundGeometry = /** @class */ (function (_super) {
  40173. __extends(GroundGeometry, _super);
  40174. /**
  40175. * Creates a new ground geometry
  40176. * @param id defines the unique ID of the geometry
  40177. * @param scene defines the hosting scene
  40178. * @param width defines the width of the ground
  40179. * @param height defines the height of the ground
  40180. * @param subdivisions defines the subdivisions to apply to the ground
  40181. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40182. * @param mesh defines the hosting mesh (can be null)
  40183. */
  40184. function GroundGeometry(id, scene,
  40185. /**
  40186. * Defines the width of the ground
  40187. */
  40188. width,
  40189. /**
  40190. * Defines the height of the ground
  40191. */
  40192. height,
  40193. /**
  40194. * Defines the subdivisions to apply to the ground
  40195. */
  40196. subdivisions, canBeRegenerated, mesh) {
  40197. if (mesh === void 0) { mesh = null; }
  40198. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40199. _this.width = width;
  40200. _this.height = height;
  40201. _this.subdivisions = subdivisions;
  40202. return _this;
  40203. }
  40204. GroundGeometry.prototype._regenerateVertexData = function () {
  40205. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40206. };
  40207. GroundGeometry.prototype.copy = function (id) {
  40208. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40209. };
  40210. GroundGeometry.prototype.serialize = function () {
  40211. var serializationObject = _super.prototype.serialize.call(this);
  40212. serializationObject.width = this.width;
  40213. serializationObject.height = this.height;
  40214. serializationObject.subdivisions = this.subdivisions;
  40215. return serializationObject;
  40216. };
  40217. GroundGeometry.Parse = function (parsedGround, scene) {
  40218. if (scene.getGeometryByID(parsedGround.id)) {
  40219. return null; // null since geometry could be something else than a ground...
  40220. }
  40221. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40222. if (BABYLON.Tags) {
  40223. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40224. }
  40225. scene.pushGeometry(ground, true);
  40226. return ground;
  40227. };
  40228. return GroundGeometry;
  40229. }(_PrimitiveGeometry));
  40230. BABYLON.GroundGeometry = GroundGeometry;
  40231. /**
  40232. * Creates a tiled ground geometry
  40233. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40234. */
  40235. var TiledGroundGeometry = /** @class */ (function (_super) {
  40236. __extends(TiledGroundGeometry, _super);
  40237. /**
  40238. * Creates a tiled ground geometry
  40239. * @param id defines the unique ID of the geometry
  40240. * @param scene defines the hosting scene
  40241. * @param xmin defines the minimum value on X axis
  40242. * @param zmin defines the minimum value on Z axis
  40243. * @param xmax defines the maximum value on X axis
  40244. * @param zmax defines the maximum value on Z axis
  40245. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40246. * @param precision defines the precision to use when computing the tiles
  40247. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40248. * @param mesh defines the hosting mesh (can be null)
  40249. */
  40250. function TiledGroundGeometry(id, scene,
  40251. /**
  40252. * Defines the minimum value on X axis
  40253. */
  40254. xmin,
  40255. /**
  40256. * Defines the minimum value on Z axis
  40257. */
  40258. zmin,
  40259. /**
  40260. * Defines the maximum value on X axis
  40261. */
  40262. xmax,
  40263. /**
  40264. * Defines the maximum value on Z axis
  40265. */
  40266. zmax,
  40267. /**
  40268. * Defines the subdivisions to apply to the ground
  40269. */
  40270. subdivisions,
  40271. /**
  40272. * Defines the precision to use when computing the tiles
  40273. */
  40274. precision, canBeRegenerated, mesh) {
  40275. if (mesh === void 0) { mesh = null; }
  40276. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40277. _this.xmin = xmin;
  40278. _this.zmin = zmin;
  40279. _this.xmax = xmax;
  40280. _this.zmax = zmax;
  40281. _this.subdivisions = subdivisions;
  40282. _this.precision = precision;
  40283. return _this;
  40284. }
  40285. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40286. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40287. };
  40288. TiledGroundGeometry.prototype.copy = function (id) {
  40289. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40290. };
  40291. return TiledGroundGeometry;
  40292. }(_PrimitiveGeometry));
  40293. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40294. /**
  40295. * Creates a plane geometry
  40296. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40297. */
  40298. var PlaneGeometry = /** @class */ (function (_super) {
  40299. __extends(PlaneGeometry, _super);
  40300. /**
  40301. * Creates a plane geometry
  40302. * @param id defines the unique ID of the geometry
  40303. * @param scene defines the hosting scene
  40304. * @param size defines the size of the plane (width === height)
  40305. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40306. * @param mesh defines the hosting mesh (can be null)
  40307. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40308. */
  40309. function PlaneGeometry(id, scene,
  40310. /**
  40311. * Defines the size of the plane (width === height)
  40312. */
  40313. size, canBeRegenerated, mesh,
  40314. /**
  40315. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40316. */
  40317. side) {
  40318. if (mesh === void 0) { mesh = null; }
  40319. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40320. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40321. _this.size = size;
  40322. _this.side = side;
  40323. return _this;
  40324. }
  40325. PlaneGeometry.prototype._regenerateVertexData = function () {
  40326. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40327. };
  40328. PlaneGeometry.prototype.copy = function (id) {
  40329. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40330. };
  40331. PlaneGeometry.prototype.serialize = function () {
  40332. var serializationObject = _super.prototype.serialize.call(this);
  40333. serializationObject.size = this.size;
  40334. return serializationObject;
  40335. };
  40336. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40337. if (scene.getGeometryByID(parsedPlane.id)) {
  40338. return null; // null since geometry could be something else than a ground...
  40339. }
  40340. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40341. if (BABYLON.Tags) {
  40342. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40343. }
  40344. scene.pushGeometry(plane, true);
  40345. return plane;
  40346. };
  40347. return PlaneGeometry;
  40348. }(_PrimitiveGeometry));
  40349. BABYLON.PlaneGeometry = PlaneGeometry;
  40350. /**
  40351. * Creates a torus knot geometry
  40352. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40353. */
  40354. var TorusKnotGeometry = /** @class */ (function (_super) {
  40355. __extends(TorusKnotGeometry, _super);
  40356. /**
  40357. * Creates a torus knot geometry
  40358. * @param id defines the unique ID of the geometry
  40359. * @param scene defines the hosting scene
  40360. * @param radius defines the radius of the torus knot
  40361. * @param tube defines the thickness of the torus knot tube
  40362. * @param radialSegments defines the number of radial segments
  40363. * @param tubularSegments defines the number of tubular segments
  40364. * @param p defines the first number of windings
  40365. * @param q defines the second number of windings
  40366. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40367. * @param mesh defines the hosting mesh (can be null)
  40368. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40369. */
  40370. function TorusKnotGeometry(id, scene,
  40371. /**
  40372. * Defines the radius of the torus knot
  40373. */
  40374. radius,
  40375. /**
  40376. * Defines the thickness of the torus knot tube
  40377. */
  40378. tube,
  40379. /**
  40380. * Defines the number of radial segments
  40381. */
  40382. radialSegments,
  40383. /**
  40384. * Defines the number of tubular segments
  40385. */
  40386. tubularSegments,
  40387. /**
  40388. * Defines the first number of windings
  40389. */
  40390. p,
  40391. /**
  40392. * Defines the second number of windings
  40393. */
  40394. q, canBeRegenerated, mesh,
  40395. /**
  40396. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40397. */
  40398. side) {
  40399. if (mesh === void 0) { mesh = null; }
  40400. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40401. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40402. _this.radius = radius;
  40403. _this.tube = tube;
  40404. _this.radialSegments = radialSegments;
  40405. _this.tubularSegments = tubularSegments;
  40406. _this.p = p;
  40407. _this.q = q;
  40408. _this.side = side;
  40409. return _this;
  40410. }
  40411. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40412. 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 });
  40413. };
  40414. TorusKnotGeometry.prototype.copy = function (id) {
  40415. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40416. };
  40417. TorusKnotGeometry.prototype.serialize = function () {
  40418. var serializationObject = _super.prototype.serialize.call(this);
  40419. serializationObject.radius = this.radius;
  40420. serializationObject.tube = this.tube;
  40421. serializationObject.radialSegments = this.radialSegments;
  40422. serializationObject.tubularSegments = this.tubularSegments;
  40423. serializationObject.p = this.p;
  40424. serializationObject.q = this.q;
  40425. return serializationObject;
  40426. };
  40427. ;
  40428. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40429. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40430. return null; // null since geometry could be something else than a ground...
  40431. }
  40432. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40433. if (BABYLON.Tags) {
  40434. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40435. }
  40436. scene.pushGeometry(torusKnot, true);
  40437. return torusKnot;
  40438. };
  40439. return TorusKnotGeometry;
  40440. }(_PrimitiveGeometry));
  40441. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40442. //}
  40443. })(BABYLON || (BABYLON = {}));
  40444. //# sourceMappingURL=babylon.geometry.js.map
  40445. var BABYLON;
  40446. (function (BABYLON) {
  40447. /**
  40448. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40449. */
  40450. var PerformanceMonitor = /** @class */ (function () {
  40451. /**
  40452. * constructor
  40453. * @param frameSampleSize The number of samples required to saturate the sliding window
  40454. */
  40455. function PerformanceMonitor(frameSampleSize) {
  40456. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40457. this._enabled = true;
  40458. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40459. }
  40460. /**
  40461. * Samples current frame
  40462. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40463. */
  40464. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40465. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40466. if (!this._enabled)
  40467. return;
  40468. if (this._lastFrameTimeMs != null) {
  40469. var dt = timeMs - this._lastFrameTimeMs;
  40470. this._rollingFrameTime.add(dt);
  40471. }
  40472. this._lastFrameTimeMs = timeMs;
  40473. };
  40474. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40475. /**
  40476. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40477. * @return Average frame time in milliseconds
  40478. */
  40479. get: function () {
  40480. return this._rollingFrameTime.average;
  40481. },
  40482. enumerable: true,
  40483. configurable: true
  40484. });
  40485. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40486. /**
  40487. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40488. * @return Frame time variance in milliseconds squared
  40489. */
  40490. get: function () {
  40491. return this._rollingFrameTime.variance;
  40492. },
  40493. enumerable: true,
  40494. configurable: true
  40495. });
  40496. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40497. /**
  40498. * Returns the frame time of the most recent frame
  40499. * @return Frame time in milliseconds
  40500. */
  40501. get: function () {
  40502. return this._rollingFrameTime.history(0);
  40503. },
  40504. enumerable: true,
  40505. configurable: true
  40506. });
  40507. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40508. /**
  40509. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40510. * @return Framerate in frames per second
  40511. */
  40512. get: function () {
  40513. return 1000.0 / this._rollingFrameTime.average;
  40514. },
  40515. enumerable: true,
  40516. configurable: true
  40517. });
  40518. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40519. /**
  40520. * Returns the average framerate in frames per second using the most recent frame time
  40521. * @return Framerate in frames per second
  40522. */
  40523. get: function () {
  40524. var history = this._rollingFrameTime.history(0);
  40525. if (history === 0) {
  40526. return 0;
  40527. }
  40528. return 1000.0 / history;
  40529. },
  40530. enumerable: true,
  40531. configurable: true
  40532. });
  40533. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40534. /**
  40535. * Returns true if enough samples have been taken to completely fill the sliding window
  40536. * @return true if saturated
  40537. */
  40538. get: function () {
  40539. return this._rollingFrameTime.isSaturated();
  40540. },
  40541. enumerable: true,
  40542. configurable: true
  40543. });
  40544. /**
  40545. * Enables contributions to the sliding window sample set
  40546. */
  40547. PerformanceMonitor.prototype.enable = function () {
  40548. this._enabled = true;
  40549. };
  40550. /**
  40551. * Disables contributions to the sliding window sample set
  40552. * Samples will not be interpolated over the disabled period
  40553. */
  40554. PerformanceMonitor.prototype.disable = function () {
  40555. this._enabled = false;
  40556. //clear last sample to avoid interpolating over the disabled period when next enabled
  40557. this._lastFrameTimeMs = null;
  40558. };
  40559. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40560. /**
  40561. * Returns true if sampling is enabled
  40562. * @return true if enabled
  40563. */
  40564. get: function () {
  40565. return this._enabled;
  40566. },
  40567. enumerable: true,
  40568. configurable: true
  40569. });
  40570. /**
  40571. * Resets performance monitor
  40572. */
  40573. PerformanceMonitor.prototype.reset = function () {
  40574. //clear last sample to avoid interpolating over the disabled period when next enabled
  40575. this._lastFrameTimeMs = null;
  40576. //wipe record
  40577. this._rollingFrameTime.reset();
  40578. };
  40579. return PerformanceMonitor;
  40580. }());
  40581. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40582. /**
  40583. * RollingAverage
  40584. *
  40585. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40586. */
  40587. var RollingAverage = /** @class */ (function () {
  40588. /**
  40589. * constructor
  40590. * @param length The number of samples required to saturate the sliding window
  40591. */
  40592. function RollingAverage(length) {
  40593. this._samples = new Array(length);
  40594. this.reset();
  40595. }
  40596. /**
  40597. * Adds a sample to the sample set
  40598. * @param v The sample value
  40599. */
  40600. RollingAverage.prototype.add = function (v) {
  40601. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40602. var delta;
  40603. //we need to check if we've already wrapped round
  40604. if (this.isSaturated()) {
  40605. //remove bottom of stack from mean
  40606. var bottomValue = this._samples[this._pos];
  40607. delta = bottomValue - this.average;
  40608. this.average -= delta / (this._sampleCount - 1);
  40609. this._m2 -= delta * (bottomValue - this.average);
  40610. }
  40611. else {
  40612. this._sampleCount++;
  40613. }
  40614. //add new value to mean
  40615. delta = v - this.average;
  40616. this.average += delta / (this._sampleCount);
  40617. this._m2 += delta * (v - this.average);
  40618. //set the new variance
  40619. this.variance = this._m2 / (this._sampleCount - 1);
  40620. this._samples[this._pos] = v;
  40621. this._pos++;
  40622. this._pos %= this._samples.length; //positive wrap around
  40623. };
  40624. /**
  40625. * Returns previously added values or null if outside of history or outside the sliding window domain
  40626. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40627. * @return Value previously recorded with add() or null if outside of range
  40628. */
  40629. RollingAverage.prototype.history = function (i) {
  40630. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40631. return 0;
  40632. }
  40633. var i0 = this._wrapPosition(this._pos - 1.0);
  40634. return this._samples[this._wrapPosition(i0 - i)];
  40635. };
  40636. /**
  40637. * Returns true if enough samples have been taken to completely fill the sliding window
  40638. * @return true if sample-set saturated
  40639. */
  40640. RollingAverage.prototype.isSaturated = function () {
  40641. return this._sampleCount >= this._samples.length;
  40642. };
  40643. /**
  40644. * Resets the rolling average (equivalent to 0 samples taken so far)
  40645. */
  40646. RollingAverage.prototype.reset = function () {
  40647. this.average = 0;
  40648. this.variance = 0;
  40649. this._sampleCount = 0;
  40650. this._pos = 0;
  40651. this._m2 = 0;
  40652. };
  40653. /**
  40654. * Wraps a value around the sample range boundaries
  40655. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40656. * @return Wrapped position in sample range
  40657. */
  40658. RollingAverage.prototype._wrapPosition = function (i) {
  40659. var max = this._samples.length;
  40660. return ((i % max) + max) % max;
  40661. };
  40662. return RollingAverage;
  40663. }());
  40664. BABYLON.RollingAverage = RollingAverage;
  40665. })(BABYLON || (BABYLON = {}));
  40666. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40667. var BABYLON;
  40668. (function (BABYLON) {
  40669. /**
  40670. * "Static Class" containing the most commonly used helper while dealing with material for
  40671. * rendering purpose.
  40672. *
  40673. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40674. *
  40675. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40676. */
  40677. var MaterialHelper = /** @class */ (function () {
  40678. function MaterialHelper() {
  40679. }
  40680. /**
  40681. * Bind the current view position to an effect.
  40682. * @param effect The effect to be bound
  40683. * @param scene The scene the eyes position is used from
  40684. */
  40685. MaterialHelper.BindEyePosition = function (effect, scene) {
  40686. if (scene._forcedViewPosition) {
  40687. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40688. return;
  40689. }
  40690. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40691. };
  40692. /**
  40693. * Helps preparing the defines values about the UVs in used in the effect.
  40694. * UVs are shared as much as we can accross chanels in the shaders.
  40695. * @param texture The texture we are preparing the UVs for
  40696. * @param defines The defines to update
  40697. * @param key The chanel key "diffuse", "specular"... used in the shader
  40698. */
  40699. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40700. defines._needUVs = true;
  40701. defines[key] = true;
  40702. if (texture.getTextureMatrix().isIdentity(true)) {
  40703. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40704. if (texture.coordinatesIndex === 0) {
  40705. defines["MAINUV1"] = true;
  40706. }
  40707. else {
  40708. defines["MAINUV2"] = true;
  40709. }
  40710. }
  40711. else {
  40712. defines[key + "DIRECTUV"] = 0;
  40713. }
  40714. };
  40715. /**
  40716. * Binds a texture matrix value to its corrsponding uniform
  40717. * @param texture The texture to bind the matrix for
  40718. * @param uniformBuffer The uniform buffer receivin the data
  40719. * @param key The chanel key "diffuse", "specular"... used in the shader
  40720. */
  40721. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40722. var matrix = texture.getTextureMatrix();
  40723. if (!matrix.isIdentity(true)) {
  40724. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40725. }
  40726. };
  40727. /**
  40728. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40729. * @param mesh defines the current mesh
  40730. * @param scene defines the current scene
  40731. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40732. * @param pointsCloud defines if point cloud rendering has to be turned on
  40733. * @param fogEnabled defines if fog has to be turned on
  40734. * @param alphaTest defines if alpha testing has to be turned on
  40735. * @param defines defines the current list of defines
  40736. */
  40737. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40738. if (defines._areMiscDirty) {
  40739. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40740. defines["POINTSIZE"] = pointsCloud;
  40741. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40742. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40743. defines["ALPHATEST"] = alphaTest;
  40744. }
  40745. };
  40746. /**
  40747. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40748. * @param scene defines the current scene
  40749. * @param engine defines the current engine
  40750. * @param defines specifies the list of active defines
  40751. * @param useInstances defines if instances have to be turned on
  40752. * @param useClipPlane defines if clip plane have to be turned on
  40753. */
  40754. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40755. if (useClipPlane === void 0) { useClipPlane = null; }
  40756. var changed = false;
  40757. if (useClipPlane == null) {
  40758. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40759. }
  40760. if (defines["CLIPPLANE"] !== useClipPlane) {
  40761. defines["CLIPPLANE"] = useClipPlane;
  40762. changed = true;
  40763. }
  40764. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40765. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40766. changed = true;
  40767. }
  40768. if (defines["INSTANCES"] !== useInstances) {
  40769. defines["INSTANCES"] = useInstances;
  40770. changed = true;
  40771. }
  40772. if (changed) {
  40773. defines.markAsUnprocessed();
  40774. }
  40775. };
  40776. /**
  40777. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40778. * @param mesh The mesh containing the geometry data we will draw
  40779. * @param defines The defines to update
  40780. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40781. * @param useBones Precise whether bones should be used or not (override mesh info)
  40782. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40783. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40784. * @returns false if defines are considered not dirty and have not been checked
  40785. */
  40786. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40787. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40788. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40789. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40790. return false;
  40791. }
  40792. defines._normals = defines._needNormals;
  40793. defines._uvs = defines._needUVs;
  40794. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40795. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40796. defines["TANGENT"] = true;
  40797. }
  40798. if (defines._needUVs) {
  40799. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40800. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40801. }
  40802. else {
  40803. defines["UV1"] = false;
  40804. defines["UV2"] = false;
  40805. }
  40806. if (useVertexColor) {
  40807. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40808. defines["VERTEXCOLOR"] = hasVertexColors;
  40809. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40810. }
  40811. if (useBones) {
  40812. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40813. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40814. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40815. }
  40816. else {
  40817. defines["NUM_BONE_INFLUENCERS"] = 0;
  40818. defines["BonesPerMesh"] = 0;
  40819. }
  40820. }
  40821. if (useMorphTargets) {
  40822. var manager = mesh.morphTargetManager;
  40823. if (manager) {
  40824. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40825. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40826. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40827. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40828. }
  40829. else {
  40830. defines["MORPHTARGETS_TANGENT"] = false;
  40831. defines["MORPHTARGETS_NORMAL"] = false;
  40832. defines["MORPHTARGETS"] = false;
  40833. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40834. }
  40835. }
  40836. return true;
  40837. };
  40838. /**
  40839. * Prepares the defines related to the light information passed in parameter
  40840. * @param scene The scene we are intending to draw
  40841. * @param mesh The mesh the effect is compiling for
  40842. * @param defines The defines to update
  40843. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40844. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40845. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40846. * @returns true if normals will be required for the rest of the effect
  40847. */
  40848. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40849. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40850. if (disableLighting === void 0) { disableLighting = false; }
  40851. if (!defines._areLightsDirty) {
  40852. return defines._needNormals;
  40853. }
  40854. var lightIndex = 0;
  40855. var needNormals = false;
  40856. var needRebuild = false;
  40857. var lightmapMode = false;
  40858. var shadowEnabled = false;
  40859. var specularEnabled = false;
  40860. if (scene.lightsEnabled && !disableLighting) {
  40861. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40862. var light = _a[_i];
  40863. needNormals = true;
  40864. if (defines["LIGHT" + lightIndex] === undefined) {
  40865. needRebuild = true;
  40866. }
  40867. defines["LIGHT" + lightIndex] = true;
  40868. defines["SPOTLIGHT" + lightIndex] = false;
  40869. defines["HEMILIGHT" + lightIndex] = false;
  40870. defines["POINTLIGHT" + lightIndex] = false;
  40871. defines["DIRLIGHT" + lightIndex] = false;
  40872. light.prepareLightSpecificDefines(defines, lightIndex);
  40873. // Specular
  40874. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40875. specularEnabled = true;
  40876. }
  40877. // Shadows
  40878. defines["SHADOW" + lightIndex] = false;
  40879. defines["SHADOWPCF" + lightIndex] = false;
  40880. defines["SHADOWPCSS" + lightIndex] = false;
  40881. defines["SHADOWPOISSON" + lightIndex] = false;
  40882. defines["SHADOWESM" + lightIndex] = false;
  40883. defines["SHADOWCUBE" + lightIndex] = false;
  40884. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40885. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40886. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40887. var shadowGenerator = light.getShadowGenerator();
  40888. if (shadowGenerator) {
  40889. var shadowMap = shadowGenerator.getShadowMap();
  40890. if (shadowMap) {
  40891. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40892. shadowEnabled = true;
  40893. shadowGenerator.prepareDefines(defines, lightIndex);
  40894. }
  40895. }
  40896. }
  40897. }
  40898. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40899. lightmapMode = true;
  40900. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40901. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40902. }
  40903. else {
  40904. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40905. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40906. }
  40907. lightIndex++;
  40908. if (lightIndex === maxSimultaneousLights)
  40909. break;
  40910. }
  40911. }
  40912. defines["SPECULARTERM"] = specularEnabled;
  40913. defines["SHADOWS"] = shadowEnabled;
  40914. // Resetting all other lights if any
  40915. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40916. if (defines["LIGHT" + index] !== undefined) {
  40917. defines["LIGHT" + index] = false;
  40918. defines["HEMILIGHT" + lightIndex] = false;
  40919. defines["POINTLIGHT" + lightIndex] = false;
  40920. defines["DIRLIGHT" + lightIndex] = false;
  40921. defines["SPOTLIGHT" + lightIndex] = false;
  40922. defines["SHADOW" + lightIndex] = false;
  40923. }
  40924. }
  40925. var caps = scene.getEngine().getCaps();
  40926. if (defines["SHADOWFLOAT"] === undefined) {
  40927. needRebuild = true;
  40928. }
  40929. defines["SHADOWFLOAT"] = shadowEnabled &&
  40930. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40931. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40932. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40933. if (needRebuild) {
  40934. defines.rebuild();
  40935. }
  40936. return needNormals;
  40937. };
  40938. /**
  40939. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40940. * that won t be acctive due to defines being turned off.
  40941. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40942. * @param samplersList The samplers list
  40943. * @param defines The defines helping in the list generation
  40944. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40945. */
  40946. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40947. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40948. var uniformsList;
  40949. var uniformBuffersList = null;
  40950. if (uniformsListOrOptions.uniformsNames) {
  40951. var options = uniformsListOrOptions;
  40952. uniformsList = options.uniformsNames;
  40953. uniformBuffersList = options.uniformBuffersNames;
  40954. samplersList = options.samplers;
  40955. defines = options.defines;
  40956. maxSimultaneousLights = options.maxSimultaneousLights;
  40957. }
  40958. else {
  40959. uniformsList = uniformsListOrOptions;
  40960. if (!samplersList) {
  40961. samplersList = [];
  40962. }
  40963. }
  40964. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40965. if (!defines["LIGHT" + lightIndex]) {
  40966. break;
  40967. }
  40968. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40969. if (uniformBuffersList) {
  40970. uniformBuffersList.push("Light" + lightIndex);
  40971. }
  40972. samplersList.push("shadowSampler" + lightIndex);
  40973. samplersList.push("depthSampler" + lightIndex);
  40974. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40975. samplersList.push("projectionLightSampler" + lightIndex);
  40976. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40977. }
  40978. }
  40979. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40980. uniformsList.push("morphTargetInfluences");
  40981. }
  40982. };
  40983. /**
  40984. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40985. * @param defines The defines to update while falling back
  40986. * @param fallbacks The authorized effect fallbacks
  40987. * @param maxSimultaneousLights The maximum number of lights allowed
  40988. * @param rank the current rank of the Effect
  40989. * @returns The newly affected rank
  40990. */
  40991. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40992. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40993. if (rank === void 0) { rank = 0; }
  40994. var lightFallbackRank = 0;
  40995. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40996. if (!defines["LIGHT" + lightIndex]) {
  40997. break;
  40998. }
  40999. if (lightIndex > 0) {
  41000. lightFallbackRank = rank + lightIndex;
  41001. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41002. }
  41003. if (!defines["SHADOWS"]) {
  41004. if (defines["SHADOW" + lightIndex]) {
  41005. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41006. }
  41007. if (defines["SHADOWPCF" + lightIndex]) {
  41008. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41009. }
  41010. if (defines["SHADOWPCSS" + lightIndex]) {
  41011. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41012. }
  41013. if (defines["SHADOWPOISSON" + lightIndex]) {
  41014. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41015. }
  41016. if (defines["SHADOWESM" + lightIndex]) {
  41017. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41018. }
  41019. }
  41020. }
  41021. return lightFallbackRank++;
  41022. };
  41023. /**
  41024. * Prepares the list of attributes required for morph targets according to the effect defines.
  41025. * @param attribs The current list of supported attribs
  41026. * @param mesh The mesh to prepare the morph targets attributes for
  41027. * @param defines The current Defines of the effect
  41028. */
  41029. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41030. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41031. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41032. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41033. var manager = mesh.morphTargetManager;
  41034. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41035. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41036. for (var index = 0; index < influencers; index++) {
  41037. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41038. if (normal) {
  41039. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41040. }
  41041. if (tangent) {
  41042. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41043. }
  41044. if (attribs.length > maxAttributesCount) {
  41045. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41046. }
  41047. }
  41048. }
  41049. };
  41050. /**
  41051. * Prepares the list of attributes required for bones according to the effect defines.
  41052. * @param attribs The current list of supported attribs
  41053. * @param mesh The mesh to prepare the bones attributes for
  41054. * @param defines The current Defines of the effect
  41055. * @param fallbacks The current efffect fallback strategy
  41056. */
  41057. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41058. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41059. fallbacks.addCPUSkinningFallback(0, mesh);
  41060. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41061. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41062. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41063. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41064. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41065. }
  41066. }
  41067. };
  41068. /**
  41069. * Prepares the list of attributes required for instances according to the effect defines.
  41070. * @param attribs The current list of supported attribs
  41071. * @param defines The current Defines of the effect
  41072. */
  41073. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41074. if (defines["INSTANCES"]) {
  41075. attribs.push("world0");
  41076. attribs.push("world1");
  41077. attribs.push("world2");
  41078. attribs.push("world3");
  41079. }
  41080. };
  41081. /**
  41082. * Binds the light shadow information to the effect for the given mesh.
  41083. * @param light The light containing the generator
  41084. * @param scene The scene the lights belongs to
  41085. * @param mesh The mesh we are binding the information to render
  41086. * @param lightIndex The light index in the effect used to render the mesh
  41087. * @param effect The effect we are binding the data to
  41088. */
  41089. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41090. if (light.shadowEnabled && mesh.receiveShadows) {
  41091. var shadowGenerator = light.getShadowGenerator();
  41092. if (shadowGenerator) {
  41093. shadowGenerator.bindShadowLight(lightIndex, effect);
  41094. }
  41095. }
  41096. };
  41097. /**
  41098. * Binds the light information to the effect.
  41099. * @param light The light containing the generator
  41100. * @param effect The effect we are binding the data to
  41101. * @param lightIndex The light index in the effect used to render
  41102. */
  41103. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41104. light.transferToEffect(effect, lightIndex + "");
  41105. };
  41106. /**
  41107. * Binds the lights information from the scene to the effect for the given mesh.
  41108. * @param scene The scene the lights belongs to
  41109. * @param mesh The mesh we are binding the information to render
  41110. * @param effect The effect we are binding the data to
  41111. * @param defines The generated defines for the effect
  41112. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41113. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41114. */
  41115. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41116. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41117. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41118. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41119. for (var i = 0; i < len; i++) {
  41120. var light = mesh._lightSources[i];
  41121. var iAsString = i.toString();
  41122. var scaledIntensity = light.getScaledIntensity();
  41123. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41124. MaterialHelper.BindLightProperties(light, effect, i);
  41125. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41126. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41127. if (defines["SPECULARTERM"]) {
  41128. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41129. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41130. }
  41131. // Shadows
  41132. if (scene.shadowsEnabled) {
  41133. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41134. }
  41135. light._uniformBuffer.update();
  41136. }
  41137. };
  41138. /**
  41139. * Binds the fog information from the scene to the effect for the given mesh.
  41140. * @param scene The scene the lights belongs to
  41141. * @param mesh The mesh we are binding the information to render
  41142. * @param effect The effect we are binding the data to
  41143. */
  41144. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41145. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41146. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41147. effect.setColor3("vFogColor", scene.fogColor);
  41148. }
  41149. };
  41150. /**
  41151. * Binds the bones information from the mesh to the effect.
  41152. * @param mesh The mesh we are binding the information to render
  41153. * @param effect The effect we are binding the data to
  41154. */
  41155. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41156. if (!effect || !mesh) {
  41157. return;
  41158. }
  41159. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41160. mesh.computeBonesUsingShaders = false;
  41161. }
  41162. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41163. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41164. if (matrices) {
  41165. effect.setMatrices("mBones", matrices);
  41166. }
  41167. }
  41168. };
  41169. /**
  41170. * Binds the morph targets information from the mesh to the effect.
  41171. * @param abstractMesh The mesh we are binding the information to render
  41172. * @param effect The effect we are binding the data to
  41173. */
  41174. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41175. var manager = abstractMesh.morphTargetManager;
  41176. if (!abstractMesh || !manager) {
  41177. return;
  41178. }
  41179. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41180. };
  41181. /**
  41182. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41183. * @param defines The generated defines used in the effect
  41184. * @param effect The effect we are binding the data to
  41185. * @param scene The scene we are willing to render with logarithmic scale for
  41186. */
  41187. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41188. if (defines["LOGARITHMICDEPTH"]) {
  41189. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41190. }
  41191. };
  41192. /**
  41193. * Binds the clip plane information from the scene to the effect.
  41194. * @param scene The scene the clip plane information are extracted from
  41195. * @param effect The effect we are binding the data to
  41196. */
  41197. MaterialHelper.BindClipPlane = function (effect, scene) {
  41198. if (scene.clipPlane) {
  41199. var clipPlane = scene.clipPlane;
  41200. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41201. }
  41202. };
  41203. return MaterialHelper;
  41204. }());
  41205. BABYLON.MaterialHelper = MaterialHelper;
  41206. })(BABYLON || (BABYLON = {}));
  41207. //# sourceMappingURL=babylon.materialHelper.js.map
  41208. var BABYLON;
  41209. (function (BABYLON) {
  41210. var PushMaterial = /** @class */ (function (_super) {
  41211. __extends(PushMaterial, _super);
  41212. function PushMaterial(name, scene) {
  41213. var _this = _super.call(this, name, scene) || this;
  41214. _this._normalMatrix = new BABYLON.Matrix();
  41215. _this.storeEffectOnSubMeshes = true;
  41216. return _this;
  41217. }
  41218. PushMaterial.prototype.getEffect = function () {
  41219. return this._activeEffect;
  41220. };
  41221. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41222. if (!mesh) {
  41223. return false;
  41224. }
  41225. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41226. return true;
  41227. }
  41228. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41229. };
  41230. /**
  41231. * Binds the given world matrix to the active effect
  41232. *
  41233. * @param world the matrix to bind
  41234. */
  41235. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41236. this._activeEffect.setMatrix("world", world);
  41237. };
  41238. /**
  41239. * Binds the given normal matrix to the active effect
  41240. *
  41241. * @param normalMatrix the matrix to bind
  41242. */
  41243. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41244. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41245. };
  41246. PushMaterial.prototype.bind = function (world, mesh) {
  41247. if (!mesh) {
  41248. return;
  41249. }
  41250. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41251. };
  41252. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41253. if (effect === void 0) { effect = null; }
  41254. _super.prototype._afterBind.call(this, mesh);
  41255. this.getScene()._cachedEffect = effect;
  41256. };
  41257. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41258. if (visibility === void 0) { visibility = 1; }
  41259. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41260. };
  41261. return PushMaterial;
  41262. }(BABYLON.Material));
  41263. BABYLON.PushMaterial = PushMaterial;
  41264. })(BABYLON || (BABYLON = {}));
  41265. //# sourceMappingURL=babylon.pushMaterial.js.map
  41266. var BABYLON;
  41267. (function (BABYLON) {
  41268. /** @hidden */
  41269. var StandardMaterialDefines = /** @class */ (function (_super) {
  41270. __extends(StandardMaterialDefines, _super);
  41271. function StandardMaterialDefines() {
  41272. var _this = _super.call(this) || this;
  41273. _this.MAINUV1 = false;
  41274. _this.MAINUV2 = false;
  41275. _this.DIFFUSE = false;
  41276. _this.DIFFUSEDIRECTUV = 0;
  41277. _this.AMBIENT = false;
  41278. _this.AMBIENTDIRECTUV = 0;
  41279. _this.OPACITY = false;
  41280. _this.OPACITYDIRECTUV = 0;
  41281. _this.OPACITYRGB = false;
  41282. _this.REFLECTION = false;
  41283. _this.EMISSIVE = false;
  41284. _this.EMISSIVEDIRECTUV = 0;
  41285. _this.SPECULAR = false;
  41286. _this.SPECULARDIRECTUV = 0;
  41287. _this.BUMP = false;
  41288. _this.BUMPDIRECTUV = 0;
  41289. _this.PARALLAX = false;
  41290. _this.PARALLAXOCCLUSION = false;
  41291. _this.SPECULAROVERALPHA = false;
  41292. _this.CLIPPLANE = false;
  41293. _this.ALPHATEST = false;
  41294. _this.DEPTHPREPASS = false;
  41295. _this.ALPHAFROMDIFFUSE = false;
  41296. _this.POINTSIZE = false;
  41297. _this.FOG = false;
  41298. _this.SPECULARTERM = false;
  41299. _this.DIFFUSEFRESNEL = false;
  41300. _this.OPACITYFRESNEL = false;
  41301. _this.REFLECTIONFRESNEL = false;
  41302. _this.REFRACTIONFRESNEL = false;
  41303. _this.EMISSIVEFRESNEL = false;
  41304. _this.FRESNEL = false;
  41305. _this.NORMAL = false;
  41306. _this.UV1 = false;
  41307. _this.UV2 = false;
  41308. _this.VERTEXCOLOR = false;
  41309. _this.VERTEXALPHA = false;
  41310. _this.NUM_BONE_INFLUENCERS = 0;
  41311. _this.BonesPerMesh = 0;
  41312. _this.INSTANCES = false;
  41313. _this.GLOSSINESS = false;
  41314. _this.ROUGHNESS = false;
  41315. _this.EMISSIVEASILLUMINATION = false;
  41316. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41317. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41318. _this.LIGHTMAP = false;
  41319. _this.LIGHTMAPDIRECTUV = 0;
  41320. _this.OBJECTSPACE_NORMALMAP = false;
  41321. _this.USELIGHTMAPASSHADOWMAP = false;
  41322. _this.REFLECTIONMAP_3D = false;
  41323. _this.REFLECTIONMAP_SPHERICAL = false;
  41324. _this.REFLECTIONMAP_PLANAR = false;
  41325. _this.REFLECTIONMAP_CUBIC = false;
  41326. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41327. _this.REFLECTIONMAP_PROJECTION = false;
  41328. _this.REFLECTIONMAP_SKYBOX = false;
  41329. _this.REFLECTIONMAP_EXPLICIT = false;
  41330. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41331. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41332. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41333. _this.INVERTCUBICMAP = false;
  41334. _this.LOGARITHMICDEPTH = false;
  41335. _this.REFRACTION = false;
  41336. _this.REFRACTIONMAP_3D = false;
  41337. _this.REFLECTIONOVERALPHA = false;
  41338. _this.TWOSIDEDLIGHTING = false;
  41339. _this.SHADOWFLOAT = false;
  41340. _this.MORPHTARGETS = false;
  41341. _this.MORPHTARGETS_NORMAL = false;
  41342. _this.MORPHTARGETS_TANGENT = false;
  41343. _this.NUM_MORPH_INFLUENCERS = 0;
  41344. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41345. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41346. _this.IMAGEPROCESSING = false;
  41347. _this.VIGNETTE = false;
  41348. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41349. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41350. _this.TONEMAPPING = false;
  41351. _this.CONTRAST = false;
  41352. _this.COLORCURVES = false;
  41353. _this.COLORGRADING = false;
  41354. _this.COLORGRADING3D = false;
  41355. _this.SAMPLER3DGREENDEPTH = false;
  41356. _this.SAMPLER3DBGRMAP = false;
  41357. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41358. /**
  41359. * If the reflection texture on this material is in linear color space
  41360. * @hidden
  41361. */
  41362. _this.IS_REFLECTION_LINEAR = false;
  41363. /**
  41364. * If the refraction texture on this material is in linear color space
  41365. * @hidden
  41366. */
  41367. _this.IS_REFRACTION_LINEAR = false;
  41368. _this.EXPOSURE = false;
  41369. _this.rebuild();
  41370. return _this;
  41371. }
  41372. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41373. var modes = [
  41374. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41375. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41376. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41377. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41378. ];
  41379. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41380. var mode = modes_1[_i];
  41381. this[mode] = (mode === modeToEnable);
  41382. }
  41383. };
  41384. return StandardMaterialDefines;
  41385. }(BABYLON.MaterialDefines));
  41386. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41387. var StandardMaterial = /** @class */ (function (_super) {
  41388. __extends(StandardMaterial, _super);
  41389. function StandardMaterial(name, scene) {
  41390. var _this = _super.call(this, name, scene) || this;
  41391. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41392. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41393. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41394. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41395. _this.specularPower = 64;
  41396. _this._useAlphaFromDiffuseTexture = false;
  41397. _this._useEmissiveAsIllumination = false;
  41398. _this._linkEmissiveWithDiffuse = false;
  41399. _this._useSpecularOverAlpha = false;
  41400. _this._useReflectionOverAlpha = false;
  41401. _this._disableLighting = false;
  41402. _this._useObjectSpaceNormalMap = false;
  41403. _this._useParallax = false;
  41404. _this._useParallaxOcclusion = false;
  41405. _this.parallaxScaleBias = 0.05;
  41406. _this._roughness = 0;
  41407. _this.indexOfRefraction = 0.98;
  41408. _this.invertRefractionY = true;
  41409. /**
  41410. * Defines the alpha limits in alpha test mode
  41411. */
  41412. _this.alphaCutOff = 0.4;
  41413. _this._useLightmapAsShadowmap = false;
  41414. _this._useReflectionFresnelFromSpecular = false;
  41415. _this._useGlossinessFromSpecularMapAlpha = false;
  41416. _this._maxSimultaneousLights = 4;
  41417. /**
  41418. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41419. */
  41420. _this._invertNormalMapX = false;
  41421. /**
  41422. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41423. */
  41424. _this._invertNormalMapY = false;
  41425. /**
  41426. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41427. */
  41428. _this._twoSidedLighting = false;
  41429. _this._renderTargets = new BABYLON.SmartArray(16);
  41430. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41431. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41432. // Setup the default processing configuration to the scene.
  41433. _this._attachImageProcessingConfiguration(null);
  41434. _this.getRenderTargetTextures = function () {
  41435. _this._renderTargets.reset();
  41436. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41437. _this._renderTargets.push(_this._reflectionTexture);
  41438. }
  41439. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41440. _this._renderTargets.push(_this._refractionTexture);
  41441. }
  41442. return _this._renderTargets;
  41443. };
  41444. return _this;
  41445. }
  41446. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41447. /**
  41448. * Gets the image processing configuration used either in this material.
  41449. */
  41450. get: function () {
  41451. return this._imageProcessingConfiguration;
  41452. },
  41453. /**
  41454. * Sets the Default image processing configuration used either in the this material.
  41455. *
  41456. * If sets to null, the scene one is in use.
  41457. */
  41458. set: function (value) {
  41459. this._attachImageProcessingConfiguration(value);
  41460. // Ensure the effect will be rebuilt.
  41461. this._markAllSubMeshesAsTexturesDirty();
  41462. },
  41463. enumerable: true,
  41464. configurable: true
  41465. });
  41466. /**
  41467. * Attaches a new image processing configuration to the Standard Material.
  41468. * @param configuration
  41469. */
  41470. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41471. var _this = this;
  41472. if (configuration === this._imageProcessingConfiguration) {
  41473. return;
  41474. }
  41475. // Detaches observer.
  41476. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41477. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41478. }
  41479. // Pick the scene configuration if needed.
  41480. if (!configuration) {
  41481. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41482. }
  41483. else {
  41484. this._imageProcessingConfiguration = configuration;
  41485. }
  41486. // Attaches observer.
  41487. if (this._imageProcessingConfiguration) {
  41488. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41489. _this._markAllSubMeshesAsImageProcessingDirty();
  41490. });
  41491. }
  41492. };
  41493. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41494. /**
  41495. * Gets wether the color curves effect is enabled.
  41496. */
  41497. get: function () {
  41498. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41499. },
  41500. /**
  41501. * Sets wether the color curves effect is enabled.
  41502. */
  41503. set: function (value) {
  41504. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41505. },
  41506. enumerable: true,
  41507. configurable: true
  41508. });
  41509. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41510. /**
  41511. * Gets wether the color grading effect is enabled.
  41512. */
  41513. get: function () {
  41514. return this.imageProcessingConfiguration.colorGradingEnabled;
  41515. },
  41516. /**
  41517. * Gets wether the color grading effect is enabled.
  41518. */
  41519. set: function (value) {
  41520. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41521. },
  41522. enumerable: true,
  41523. configurable: true
  41524. });
  41525. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41526. /**
  41527. * Gets wether tonemapping is enabled or not.
  41528. */
  41529. get: function () {
  41530. return this._imageProcessingConfiguration.toneMappingEnabled;
  41531. },
  41532. /**
  41533. * Sets wether tonemapping is enabled or not
  41534. */
  41535. set: function (value) {
  41536. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41537. },
  41538. enumerable: true,
  41539. configurable: true
  41540. });
  41541. ;
  41542. ;
  41543. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41544. /**
  41545. * The camera exposure used on this material.
  41546. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41547. * This corresponds to a photographic exposure.
  41548. */
  41549. get: function () {
  41550. return this._imageProcessingConfiguration.exposure;
  41551. },
  41552. /**
  41553. * The camera exposure used on this material.
  41554. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41555. * This corresponds to a photographic exposure.
  41556. */
  41557. set: function (value) {
  41558. this._imageProcessingConfiguration.exposure = value;
  41559. },
  41560. enumerable: true,
  41561. configurable: true
  41562. });
  41563. ;
  41564. ;
  41565. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41566. /**
  41567. * Gets The camera contrast used on this material.
  41568. */
  41569. get: function () {
  41570. return this._imageProcessingConfiguration.contrast;
  41571. },
  41572. /**
  41573. * Sets The camera contrast used on this material.
  41574. */
  41575. set: function (value) {
  41576. this._imageProcessingConfiguration.contrast = value;
  41577. },
  41578. enumerable: true,
  41579. configurable: true
  41580. });
  41581. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41582. /**
  41583. * Gets the Color Grading 2D Lookup Texture.
  41584. */
  41585. get: function () {
  41586. return this._imageProcessingConfiguration.colorGradingTexture;
  41587. },
  41588. /**
  41589. * Sets the Color Grading 2D Lookup Texture.
  41590. */
  41591. set: function (value) {
  41592. this._imageProcessingConfiguration.colorGradingTexture = value;
  41593. },
  41594. enumerable: true,
  41595. configurable: true
  41596. });
  41597. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41598. /**
  41599. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41600. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41601. * 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;
  41602. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41603. */
  41604. get: function () {
  41605. return this._imageProcessingConfiguration.colorCurves;
  41606. },
  41607. /**
  41608. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41609. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41610. * 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;
  41611. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41612. */
  41613. set: function (value) {
  41614. this._imageProcessingConfiguration.colorCurves = value;
  41615. },
  41616. enumerable: true,
  41617. configurable: true
  41618. });
  41619. StandardMaterial.prototype.getClassName = function () {
  41620. return "StandardMaterial";
  41621. };
  41622. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41623. get: function () {
  41624. return this._useLogarithmicDepth;
  41625. },
  41626. set: function (value) {
  41627. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41628. this._markAllSubMeshesAsMiscDirty();
  41629. },
  41630. enumerable: true,
  41631. configurable: true
  41632. });
  41633. StandardMaterial.prototype.needAlphaBlending = function () {
  41634. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41635. };
  41636. StandardMaterial.prototype.needAlphaTesting = function () {
  41637. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41638. };
  41639. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41640. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41641. };
  41642. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41643. return this._diffuseTexture;
  41644. };
  41645. /**
  41646. * Child classes can use it to update shaders
  41647. */
  41648. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41649. if (useInstances === void 0) { useInstances = false; }
  41650. if (subMesh.effect && this.isFrozen) {
  41651. if (this._wasPreviouslyReady && subMesh.effect) {
  41652. return true;
  41653. }
  41654. }
  41655. if (!subMesh._materialDefines) {
  41656. subMesh._materialDefines = new StandardMaterialDefines();
  41657. }
  41658. var scene = this.getScene();
  41659. var defines = subMesh._materialDefines;
  41660. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41661. if (defines._renderId === scene.getRenderId()) {
  41662. return true;
  41663. }
  41664. }
  41665. var engine = scene.getEngine();
  41666. // Lights
  41667. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41668. // Textures
  41669. if (defines._areTexturesDirty) {
  41670. defines._needUVs = false;
  41671. defines.MAINUV1 = false;
  41672. defines.MAINUV2 = false;
  41673. if (scene.texturesEnabled) {
  41674. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41675. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41676. return false;
  41677. }
  41678. else {
  41679. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41680. }
  41681. }
  41682. else {
  41683. defines.DIFFUSE = false;
  41684. }
  41685. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41686. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41687. return false;
  41688. }
  41689. else {
  41690. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41691. }
  41692. }
  41693. else {
  41694. defines.AMBIENT = false;
  41695. }
  41696. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41697. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41698. return false;
  41699. }
  41700. else {
  41701. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41702. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41703. }
  41704. }
  41705. else {
  41706. defines.OPACITY = false;
  41707. }
  41708. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41709. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41710. return false;
  41711. }
  41712. else {
  41713. defines._needNormals = true;
  41714. defines.REFLECTION = true;
  41715. defines.ROUGHNESS = (this._roughness > 0);
  41716. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41717. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41718. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41719. switch (this._reflectionTexture.coordinatesMode) {
  41720. case BABYLON.Texture.EXPLICIT_MODE:
  41721. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41722. break;
  41723. case BABYLON.Texture.PLANAR_MODE:
  41724. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41725. break;
  41726. case BABYLON.Texture.PROJECTION_MODE:
  41727. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41728. break;
  41729. case BABYLON.Texture.SKYBOX_MODE:
  41730. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41731. break;
  41732. case BABYLON.Texture.SPHERICAL_MODE:
  41733. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41734. break;
  41735. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41736. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41737. break;
  41738. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41739. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41740. break;
  41741. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41742. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41743. break;
  41744. case BABYLON.Texture.CUBIC_MODE:
  41745. case BABYLON.Texture.INVCUBIC_MODE:
  41746. default:
  41747. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41748. break;
  41749. }
  41750. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41751. }
  41752. }
  41753. else {
  41754. defines.REFLECTION = false;
  41755. }
  41756. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41757. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41758. return false;
  41759. }
  41760. else {
  41761. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41762. }
  41763. }
  41764. else {
  41765. defines.EMISSIVE = false;
  41766. }
  41767. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41768. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41769. return false;
  41770. }
  41771. else {
  41772. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41773. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41774. }
  41775. }
  41776. else {
  41777. defines.LIGHTMAP = false;
  41778. }
  41779. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41780. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41781. return false;
  41782. }
  41783. else {
  41784. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41785. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41786. }
  41787. }
  41788. else {
  41789. defines.SPECULAR = false;
  41790. }
  41791. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41792. // Bump texure can not be not blocking.
  41793. if (!this._bumpTexture.isReady()) {
  41794. return false;
  41795. }
  41796. else {
  41797. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41798. defines.PARALLAX = this._useParallax;
  41799. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41800. }
  41801. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41802. }
  41803. else {
  41804. defines.BUMP = false;
  41805. }
  41806. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41807. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41808. return false;
  41809. }
  41810. else {
  41811. defines._needUVs = true;
  41812. defines.REFRACTION = true;
  41813. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41814. }
  41815. }
  41816. else {
  41817. defines.REFRACTION = false;
  41818. }
  41819. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41820. }
  41821. else {
  41822. defines.DIFFUSE = false;
  41823. defines.AMBIENT = false;
  41824. defines.OPACITY = false;
  41825. defines.REFLECTION = false;
  41826. defines.EMISSIVE = false;
  41827. defines.LIGHTMAP = false;
  41828. defines.BUMP = false;
  41829. defines.REFRACTION = false;
  41830. }
  41831. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41832. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41833. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41834. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41835. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41836. }
  41837. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41838. if (!this._imageProcessingConfiguration.isReady()) {
  41839. return false;
  41840. }
  41841. this._imageProcessingConfiguration.prepareDefines(defines);
  41842. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41843. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41844. }
  41845. if (defines._areFresnelDirty) {
  41846. if (StandardMaterial.FresnelEnabled) {
  41847. // Fresnel
  41848. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41849. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41850. this._reflectionFresnelParameters) {
  41851. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41852. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41853. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41854. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41855. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41856. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41857. defines._needNormals = true;
  41858. defines.FRESNEL = true;
  41859. }
  41860. }
  41861. else {
  41862. defines.FRESNEL = false;
  41863. }
  41864. }
  41865. // Misc.
  41866. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41867. // Attribs
  41868. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41869. // Values that need to be evaluated on every frame
  41870. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41871. // Get correct effect
  41872. if (defines.isDirty) {
  41873. defines.markAsProcessed();
  41874. scene.resetCachedMaterial();
  41875. // Fallbacks
  41876. var fallbacks = new BABYLON.EffectFallbacks();
  41877. if (defines.REFLECTION) {
  41878. fallbacks.addFallback(0, "REFLECTION");
  41879. }
  41880. if (defines.SPECULAR) {
  41881. fallbacks.addFallback(0, "SPECULAR");
  41882. }
  41883. if (defines.BUMP) {
  41884. fallbacks.addFallback(0, "BUMP");
  41885. }
  41886. if (defines.PARALLAX) {
  41887. fallbacks.addFallback(1, "PARALLAX");
  41888. }
  41889. if (defines.PARALLAXOCCLUSION) {
  41890. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41891. }
  41892. if (defines.SPECULAROVERALPHA) {
  41893. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41894. }
  41895. if (defines.FOG) {
  41896. fallbacks.addFallback(1, "FOG");
  41897. }
  41898. if (defines.POINTSIZE) {
  41899. fallbacks.addFallback(0, "POINTSIZE");
  41900. }
  41901. if (defines.LOGARITHMICDEPTH) {
  41902. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41903. }
  41904. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41905. if (defines.SPECULARTERM) {
  41906. fallbacks.addFallback(0, "SPECULARTERM");
  41907. }
  41908. if (defines.DIFFUSEFRESNEL) {
  41909. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41910. }
  41911. if (defines.OPACITYFRESNEL) {
  41912. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41913. }
  41914. if (defines.REFLECTIONFRESNEL) {
  41915. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41916. }
  41917. if (defines.EMISSIVEFRESNEL) {
  41918. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41919. }
  41920. if (defines.FRESNEL) {
  41921. fallbacks.addFallback(4, "FRESNEL");
  41922. }
  41923. //Attributes
  41924. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41925. if (defines.NORMAL) {
  41926. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41927. }
  41928. if (defines.UV1) {
  41929. attribs.push(BABYLON.VertexBuffer.UVKind);
  41930. }
  41931. if (defines.UV2) {
  41932. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41933. }
  41934. if (defines.VERTEXCOLOR) {
  41935. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41936. }
  41937. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41938. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41939. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41940. var shaderName = "default";
  41941. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41942. "vFogInfos", "vFogColor", "pointSize",
  41943. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41944. "mBones",
  41945. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41946. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41947. "vReflectionPosition", "vReflectionSize",
  41948. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41949. ];
  41950. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41951. var uniformBuffers = ["Material", "Scene"];
  41952. if (BABYLON.ImageProcessingConfiguration) {
  41953. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41954. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41955. }
  41956. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41957. uniformsNames: uniforms,
  41958. uniformBuffersNames: uniformBuffers,
  41959. samplers: samplers,
  41960. defines: defines,
  41961. maxSimultaneousLights: this._maxSimultaneousLights
  41962. });
  41963. if (this.customShaderNameResolve) {
  41964. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41965. }
  41966. var join = defines.toString();
  41967. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41968. attributes: attribs,
  41969. uniformsNames: uniforms,
  41970. uniformBuffersNames: uniformBuffers,
  41971. samplers: samplers,
  41972. defines: join,
  41973. fallbacks: fallbacks,
  41974. onCompiled: this.onCompiled,
  41975. onError: this.onError,
  41976. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41977. }, engine), defines);
  41978. this.buildUniformLayout();
  41979. }
  41980. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41981. return false;
  41982. }
  41983. defines._renderId = scene.getRenderId();
  41984. this._wasPreviouslyReady = true;
  41985. return true;
  41986. };
  41987. StandardMaterial.prototype.buildUniformLayout = function () {
  41988. // Order is important !
  41989. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41990. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41991. this._uniformBuffer.addUniform("opacityParts", 4);
  41992. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41993. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41994. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41995. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41996. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41997. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41998. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41999. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42000. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42001. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42002. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42003. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42004. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42005. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42006. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42007. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42008. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42009. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42010. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42011. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42012. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42013. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42014. this._uniformBuffer.addUniform("specularMatrix", 16);
  42015. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42016. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42017. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42018. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42019. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42020. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42021. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42022. this._uniformBuffer.addUniform("pointSize", 1);
  42023. this._uniformBuffer.create();
  42024. };
  42025. StandardMaterial.prototype.unbind = function () {
  42026. if (this._activeEffect) {
  42027. var needFlag = false;
  42028. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42029. this._activeEffect.setTexture("reflection2DSampler", null);
  42030. needFlag = true;
  42031. }
  42032. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42033. this._activeEffect.setTexture("refraction2DSampler", null);
  42034. needFlag = true;
  42035. }
  42036. if (needFlag) {
  42037. this._markAllSubMeshesAsTexturesDirty();
  42038. }
  42039. }
  42040. _super.prototype.unbind.call(this);
  42041. };
  42042. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42043. var scene = this.getScene();
  42044. var defines = subMesh._materialDefines;
  42045. if (!defines) {
  42046. return;
  42047. }
  42048. var effect = subMesh.effect;
  42049. if (!effect) {
  42050. return;
  42051. }
  42052. this._activeEffect = effect;
  42053. // Matrices
  42054. this.bindOnlyWorldMatrix(world);
  42055. // Normal Matrix
  42056. if (defines.OBJECTSPACE_NORMALMAP) {
  42057. world.toNormalMatrix(this._normalMatrix);
  42058. this.bindOnlyNormalMatrix(this._normalMatrix);
  42059. }
  42060. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42061. // Bones
  42062. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42063. if (mustRebind) {
  42064. this._uniformBuffer.bindToEffect(effect, "Material");
  42065. this.bindViewProjection(effect);
  42066. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42067. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42068. // Fresnel
  42069. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42070. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42071. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42072. }
  42073. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42074. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42075. }
  42076. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42077. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42078. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42079. }
  42080. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42081. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42082. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42083. }
  42084. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42085. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42086. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42087. }
  42088. }
  42089. // Textures
  42090. if (scene.texturesEnabled) {
  42091. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42092. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42093. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42094. if (this._diffuseTexture.hasAlpha) {
  42095. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42096. }
  42097. }
  42098. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42099. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42100. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42101. }
  42102. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42103. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42104. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42105. }
  42106. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42107. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42108. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42109. if (this._reflectionTexture.boundingBoxSize) {
  42110. var cubeTexture = this._reflectionTexture;
  42111. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42112. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42113. }
  42114. }
  42115. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42116. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42117. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42118. }
  42119. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42120. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42121. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42122. }
  42123. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42124. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42125. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42126. }
  42127. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42128. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42129. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42130. if (scene._mirroredCameraPosition) {
  42131. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42132. }
  42133. else {
  42134. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42135. }
  42136. }
  42137. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42138. var depth = 1.0;
  42139. if (!this._refractionTexture.isCube) {
  42140. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42141. if (this._refractionTexture.depth) {
  42142. depth = this._refractionTexture.depth;
  42143. }
  42144. }
  42145. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42146. }
  42147. }
  42148. // Point size
  42149. if (this.pointsCloud) {
  42150. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42151. }
  42152. if (defines.SPECULARTERM) {
  42153. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42154. }
  42155. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42156. // Diffuse
  42157. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42158. }
  42159. // Textures
  42160. if (scene.texturesEnabled) {
  42161. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42162. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42163. }
  42164. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42165. effect.setTexture("ambientSampler", this._ambientTexture);
  42166. }
  42167. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42168. effect.setTexture("opacitySampler", this._opacityTexture);
  42169. }
  42170. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42171. if (this._reflectionTexture.isCube) {
  42172. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42173. }
  42174. else {
  42175. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42176. }
  42177. }
  42178. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42179. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42180. }
  42181. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42182. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42183. }
  42184. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42185. effect.setTexture("specularSampler", this._specularTexture);
  42186. }
  42187. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42188. effect.setTexture("bumpSampler", this._bumpTexture);
  42189. }
  42190. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42191. var depth = 1.0;
  42192. if (this._refractionTexture.isCube) {
  42193. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42194. }
  42195. else {
  42196. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42197. }
  42198. }
  42199. }
  42200. // Clip plane
  42201. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42202. // Colors
  42203. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42204. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42205. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42206. }
  42207. if (mustRebind || !this.isFrozen) {
  42208. // Lights
  42209. if (scene.lightsEnabled && !this._disableLighting) {
  42210. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42211. }
  42212. // View
  42213. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42214. this.bindView(effect);
  42215. }
  42216. // Fog
  42217. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42218. // Morph targets
  42219. if (defines.NUM_MORPH_INFLUENCERS) {
  42220. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42221. }
  42222. // Log. depth
  42223. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42224. // image processing
  42225. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42226. this._imageProcessingConfiguration.bind(this._activeEffect);
  42227. }
  42228. }
  42229. this._uniformBuffer.update();
  42230. this._afterBind(mesh, this._activeEffect);
  42231. };
  42232. StandardMaterial.prototype.getAnimatables = function () {
  42233. var results = [];
  42234. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42235. results.push(this._diffuseTexture);
  42236. }
  42237. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42238. results.push(this._ambientTexture);
  42239. }
  42240. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42241. results.push(this._opacityTexture);
  42242. }
  42243. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42244. results.push(this._reflectionTexture);
  42245. }
  42246. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42247. results.push(this._emissiveTexture);
  42248. }
  42249. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42250. results.push(this._specularTexture);
  42251. }
  42252. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42253. results.push(this._bumpTexture);
  42254. }
  42255. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42256. results.push(this._lightmapTexture);
  42257. }
  42258. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42259. results.push(this._refractionTexture);
  42260. }
  42261. return results;
  42262. };
  42263. StandardMaterial.prototype.getActiveTextures = function () {
  42264. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42265. if (this._diffuseTexture) {
  42266. activeTextures.push(this._diffuseTexture);
  42267. }
  42268. if (this._ambientTexture) {
  42269. activeTextures.push(this._ambientTexture);
  42270. }
  42271. if (this._opacityTexture) {
  42272. activeTextures.push(this._opacityTexture);
  42273. }
  42274. if (this._reflectionTexture) {
  42275. activeTextures.push(this._reflectionTexture);
  42276. }
  42277. if (this._emissiveTexture) {
  42278. activeTextures.push(this._emissiveTexture);
  42279. }
  42280. if (this._specularTexture) {
  42281. activeTextures.push(this._specularTexture);
  42282. }
  42283. if (this._bumpTexture) {
  42284. activeTextures.push(this._bumpTexture);
  42285. }
  42286. if (this._lightmapTexture) {
  42287. activeTextures.push(this._lightmapTexture);
  42288. }
  42289. if (this._refractionTexture) {
  42290. activeTextures.push(this._refractionTexture);
  42291. }
  42292. return activeTextures;
  42293. };
  42294. StandardMaterial.prototype.hasTexture = function (texture) {
  42295. if (_super.prototype.hasTexture.call(this, texture)) {
  42296. return true;
  42297. }
  42298. if (this._diffuseTexture === texture) {
  42299. return true;
  42300. }
  42301. if (this._ambientTexture === texture) {
  42302. return true;
  42303. }
  42304. if (this._opacityTexture === texture) {
  42305. return true;
  42306. }
  42307. if (this._reflectionTexture === texture) {
  42308. return true;
  42309. }
  42310. if (this._emissiveTexture === texture) {
  42311. return true;
  42312. }
  42313. if (this._specularTexture === texture) {
  42314. return true;
  42315. }
  42316. if (this._bumpTexture === texture) {
  42317. return true;
  42318. }
  42319. if (this._lightmapTexture === texture) {
  42320. return true;
  42321. }
  42322. if (this._refractionTexture === texture) {
  42323. return true;
  42324. }
  42325. return false;
  42326. };
  42327. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42328. if (forceDisposeTextures) {
  42329. if (this._diffuseTexture) {
  42330. this._diffuseTexture.dispose();
  42331. }
  42332. if (this._ambientTexture) {
  42333. this._ambientTexture.dispose();
  42334. }
  42335. if (this._opacityTexture) {
  42336. this._opacityTexture.dispose();
  42337. }
  42338. if (this._reflectionTexture) {
  42339. this._reflectionTexture.dispose();
  42340. }
  42341. if (this._emissiveTexture) {
  42342. this._emissiveTexture.dispose();
  42343. }
  42344. if (this._specularTexture) {
  42345. this._specularTexture.dispose();
  42346. }
  42347. if (this._bumpTexture) {
  42348. this._bumpTexture.dispose();
  42349. }
  42350. if (this._lightmapTexture) {
  42351. this._lightmapTexture.dispose();
  42352. }
  42353. if (this._refractionTexture) {
  42354. this._refractionTexture.dispose();
  42355. }
  42356. }
  42357. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42358. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42359. }
  42360. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42361. };
  42362. StandardMaterial.prototype.clone = function (name) {
  42363. var _this = this;
  42364. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42365. result.name = name;
  42366. result.id = name;
  42367. return result;
  42368. };
  42369. StandardMaterial.prototype.serialize = function () {
  42370. return BABYLON.SerializationHelper.Serialize(this);
  42371. };
  42372. // Statics
  42373. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42374. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42375. };
  42376. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42377. get: function () {
  42378. return StandardMaterial._DiffuseTextureEnabled;
  42379. },
  42380. set: function (value) {
  42381. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42382. return;
  42383. }
  42384. StandardMaterial._DiffuseTextureEnabled = value;
  42385. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42386. },
  42387. enumerable: true,
  42388. configurable: true
  42389. });
  42390. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42391. get: function () {
  42392. return StandardMaterial._AmbientTextureEnabled;
  42393. },
  42394. set: function (value) {
  42395. if (StandardMaterial._AmbientTextureEnabled === value) {
  42396. return;
  42397. }
  42398. StandardMaterial._AmbientTextureEnabled = value;
  42399. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42400. },
  42401. enumerable: true,
  42402. configurable: true
  42403. });
  42404. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42405. get: function () {
  42406. return StandardMaterial._OpacityTextureEnabled;
  42407. },
  42408. set: function (value) {
  42409. if (StandardMaterial._OpacityTextureEnabled === value) {
  42410. return;
  42411. }
  42412. StandardMaterial._OpacityTextureEnabled = value;
  42413. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42414. },
  42415. enumerable: true,
  42416. configurable: true
  42417. });
  42418. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42419. get: function () {
  42420. return StandardMaterial._ReflectionTextureEnabled;
  42421. },
  42422. set: function (value) {
  42423. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42424. return;
  42425. }
  42426. StandardMaterial._ReflectionTextureEnabled = value;
  42427. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42428. },
  42429. enumerable: true,
  42430. configurable: true
  42431. });
  42432. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42433. get: function () {
  42434. return StandardMaterial._EmissiveTextureEnabled;
  42435. },
  42436. set: function (value) {
  42437. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42438. return;
  42439. }
  42440. StandardMaterial._EmissiveTextureEnabled = value;
  42441. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42442. },
  42443. enumerable: true,
  42444. configurable: true
  42445. });
  42446. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42447. get: function () {
  42448. return StandardMaterial._SpecularTextureEnabled;
  42449. },
  42450. set: function (value) {
  42451. if (StandardMaterial._SpecularTextureEnabled === value) {
  42452. return;
  42453. }
  42454. StandardMaterial._SpecularTextureEnabled = value;
  42455. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42456. },
  42457. enumerable: true,
  42458. configurable: true
  42459. });
  42460. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42461. get: function () {
  42462. return StandardMaterial._BumpTextureEnabled;
  42463. },
  42464. set: function (value) {
  42465. if (StandardMaterial._BumpTextureEnabled === value) {
  42466. return;
  42467. }
  42468. StandardMaterial._BumpTextureEnabled = value;
  42469. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42470. },
  42471. enumerable: true,
  42472. configurable: true
  42473. });
  42474. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42475. get: function () {
  42476. return StandardMaterial._LightmapTextureEnabled;
  42477. },
  42478. set: function (value) {
  42479. if (StandardMaterial._LightmapTextureEnabled === value) {
  42480. return;
  42481. }
  42482. StandardMaterial._LightmapTextureEnabled = value;
  42483. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42484. },
  42485. enumerable: true,
  42486. configurable: true
  42487. });
  42488. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42489. get: function () {
  42490. return StandardMaterial._RefractionTextureEnabled;
  42491. },
  42492. set: function (value) {
  42493. if (StandardMaterial._RefractionTextureEnabled === value) {
  42494. return;
  42495. }
  42496. StandardMaterial._RefractionTextureEnabled = value;
  42497. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42498. },
  42499. enumerable: true,
  42500. configurable: true
  42501. });
  42502. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42503. get: function () {
  42504. return StandardMaterial._ColorGradingTextureEnabled;
  42505. },
  42506. set: function (value) {
  42507. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42508. return;
  42509. }
  42510. StandardMaterial._ColorGradingTextureEnabled = value;
  42511. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42512. },
  42513. enumerable: true,
  42514. configurable: true
  42515. });
  42516. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42517. get: function () {
  42518. return StandardMaterial._FresnelEnabled;
  42519. },
  42520. set: function (value) {
  42521. if (StandardMaterial._FresnelEnabled === value) {
  42522. return;
  42523. }
  42524. StandardMaterial._FresnelEnabled = value;
  42525. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42526. },
  42527. enumerable: true,
  42528. configurable: true
  42529. });
  42530. // Flags used to enable or disable a type of texture for all Standard Materials
  42531. StandardMaterial._DiffuseTextureEnabled = true;
  42532. StandardMaterial._AmbientTextureEnabled = true;
  42533. StandardMaterial._OpacityTextureEnabled = true;
  42534. StandardMaterial._ReflectionTextureEnabled = true;
  42535. StandardMaterial._EmissiveTextureEnabled = true;
  42536. StandardMaterial._SpecularTextureEnabled = true;
  42537. StandardMaterial._BumpTextureEnabled = true;
  42538. StandardMaterial._LightmapTextureEnabled = true;
  42539. StandardMaterial._RefractionTextureEnabled = true;
  42540. StandardMaterial._ColorGradingTextureEnabled = true;
  42541. StandardMaterial._FresnelEnabled = true;
  42542. __decorate([
  42543. BABYLON.serializeAsTexture("diffuseTexture")
  42544. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42545. __decorate([
  42546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42547. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42548. __decorate([
  42549. BABYLON.serializeAsTexture("ambientTexture")
  42550. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42551. __decorate([
  42552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42553. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42554. __decorate([
  42555. BABYLON.serializeAsTexture("opacityTexture")
  42556. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42557. __decorate([
  42558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42559. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42560. __decorate([
  42561. BABYLON.serializeAsTexture("reflectionTexture")
  42562. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42563. __decorate([
  42564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42565. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42566. __decorate([
  42567. BABYLON.serializeAsTexture("emissiveTexture")
  42568. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42569. __decorate([
  42570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42571. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42572. __decorate([
  42573. BABYLON.serializeAsTexture("specularTexture")
  42574. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42575. __decorate([
  42576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42577. ], StandardMaterial.prototype, "specularTexture", void 0);
  42578. __decorate([
  42579. BABYLON.serializeAsTexture("bumpTexture")
  42580. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42581. __decorate([
  42582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42583. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42584. __decorate([
  42585. BABYLON.serializeAsTexture("lightmapTexture")
  42586. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42587. __decorate([
  42588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42589. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42590. __decorate([
  42591. BABYLON.serializeAsTexture("refractionTexture")
  42592. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42593. __decorate([
  42594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42595. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42596. __decorate([
  42597. BABYLON.serializeAsColor3("ambient")
  42598. ], StandardMaterial.prototype, "ambientColor", void 0);
  42599. __decorate([
  42600. BABYLON.serializeAsColor3("diffuse")
  42601. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42602. __decorate([
  42603. BABYLON.serializeAsColor3("specular")
  42604. ], StandardMaterial.prototype, "specularColor", void 0);
  42605. __decorate([
  42606. BABYLON.serializeAsColor3("emissive")
  42607. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42608. __decorate([
  42609. BABYLON.serialize()
  42610. ], StandardMaterial.prototype, "specularPower", void 0);
  42611. __decorate([
  42612. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42613. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42614. __decorate([
  42615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42616. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42617. __decorate([
  42618. BABYLON.serialize("useEmissiveAsIllumination")
  42619. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42620. __decorate([
  42621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42622. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42623. __decorate([
  42624. BABYLON.serialize("linkEmissiveWithDiffuse")
  42625. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42626. __decorate([
  42627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42628. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42629. __decorate([
  42630. BABYLON.serialize("useSpecularOverAlpha")
  42631. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42632. __decorate([
  42633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42634. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42635. __decorate([
  42636. BABYLON.serialize("useReflectionOverAlpha")
  42637. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42638. __decorate([
  42639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42640. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42641. __decorate([
  42642. BABYLON.serialize("disableLighting")
  42643. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42644. __decorate([
  42645. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42646. ], StandardMaterial.prototype, "disableLighting", void 0);
  42647. __decorate([
  42648. BABYLON.serialize("useObjectSpaceNormalMap")
  42649. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42650. __decorate([
  42651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42652. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42653. __decorate([
  42654. BABYLON.serialize("useParallax")
  42655. ], StandardMaterial.prototype, "_useParallax", void 0);
  42656. __decorate([
  42657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42658. ], StandardMaterial.prototype, "useParallax", void 0);
  42659. __decorate([
  42660. BABYLON.serialize("useParallaxOcclusion")
  42661. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42662. __decorate([
  42663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42664. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42665. __decorate([
  42666. BABYLON.serialize()
  42667. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42668. __decorate([
  42669. BABYLON.serialize("roughness")
  42670. ], StandardMaterial.prototype, "_roughness", void 0);
  42671. __decorate([
  42672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42673. ], StandardMaterial.prototype, "roughness", void 0);
  42674. __decorate([
  42675. BABYLON.serialize()
  42676. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42677. __decorate([
  42678. BABYLON.serialize()
  42679. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42680. __decorate([
  42681. BABYLON.serialize()
  42682. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42683. __decorate([
  42684. BABYLON.serialize("useLightmapAsShadowmap")
  42685. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42686. __decorate([
  42687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42688. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42689. __decorate([
  42690. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42691. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42692. __decorate([
  42693. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42694. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42695. __decorate([
  42696. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42697. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42698. __decorate([
  42699. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42700. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42701. __decorate([
  42702. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42703. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42704. __decorate([
  42705. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42706. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42707. __decorate([
  42708. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42709. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42710. __decorate([
  42711. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42712. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42713. __decorate([
  42714. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42715. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42716. __decorate([
  42717. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42718. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42719. __decorate([
  42720. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42721. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42722. __decorate([
  42723. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42724. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42725. __decorate([
  42726. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42727. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42728. __decorate([
  42729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42730. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42731. __decorate([
  42732. BABYLON.serialize("maxSimultaneousLights")
  42733. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42734. __decorate([
  42735. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42736. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42737. __decorate([
  42738. BABYLON.serialize("invertNormalMapX")
  42739. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42740. __decorate([
  42741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42742. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42743. __decorate([
  42744. BABYLON.serialize("invertNormalMapY")
  42745. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42746. __decorate([
  42747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42748. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42749. __decorate([
  42750. BABYLON.serialize("twoSidedLighting")
  42751. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42752. __decorate([
  42753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42754. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42755. __decorate([
  42756. BABYLON.serialize()
  42757. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42758. return StandardMaterial;
  42759. }(BABYLON.PushMaterial));
  42760. BABYLON.StandardMaterial = StandardMaterial;
  42761. })(BABYLON || (BABYLON = {}));
  42762. //# sourceMappingURL=babylon.standardMaterial.js.map
  42763. var BABYLON;
  42764. (function (BABYLON) {
  42765. /**
  42766. * Class representing spherical polynomial coefficients to the 3rd degree
  42767. */
  42768. var SphericalPolynomial = /** @class */ (function () {
  42769. function SphericalPolynomial() {
  42770. /**
  42771. * The x coefficients of the spherical polynomial
  42772. */
  42773. this.x = BABYLON.Vector3.Zero();
  42774. /**
  42775. * The y coefficients of the spherical polynomial
  42776. */
  42777. this.y = BABYLON.Vector3.Zero();
  42778. /**
  42779. * The z coefficients of the spherical polynomial
  42780. */
  42781. this.z = BABYLON.Vector3.Zero();
  42782. /**
  42783. * The xx coefficients of the spherical polynomial
  42784. */
  42785. this.xx = BABYLON.Vector3.Zero();
  42786. /**
  42787. * The yy coefficients of the spherical polynomial
  42788. */
  42789. this.yy = BABYLON.Vector3.Zero();
  42790. /**
  42791. * The zz coefficients of the spherical polynomial
  42792. */
  42793. this.zz = BABYLON.Vector3.Zero();
  42794. /**
  42795. * The xy coefficients of the spherical polynomial
  42796. */
  42797. this.xy = BABYLON.Vector3.Zero();
  42798. /**
  42799. * The yz coefficients of the spherical polynomial
  42800. */
  42801. this.yz = BABYLON.Vector3.Zero();
  42802. /**
  42803. * The zx coefficients of the spherical polynomial
  42804. */
  42805. this.zx = BABYLON.Vector3.Zero();
  42806. }
  42807. /**
  42808. * Adds an ambient color to the spherical polynomial
  42809. * @param color the color to add
  42810. */
  42811. SphericalPolynomial.prototype.addAmbient = function (color) {
  42812. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42813. this.xx = this.xx.add(colorVector);
  42814. this.yy = this.yy.add(colorVector);
  42815. this.zz = this.zz.add(colorVector);
  42816. };
  42817. /**
  42818. * Scales the spherical polynomial by the given amount
  42819. * @param scale the amount to scale
  42820. */
  42821. SphericalPolynomial.prototype.scale = function (scale) {
  42822. this.x = this.x.scale(scale);
  42823. this.y = this.y.scale(scale);
  42824. this.z = this.z.scale(scale);
  42825. this.xx = this.xx.scale(scale);
  42826. this.yy = this.yy.scale(scale);
  42827. this.zz = this.zz.scale(scale);
  42828. this.yz = this.yz.scale(scale);
  42829. this.zx = this.zx.scale(scale);
  42830. this.xy = this.xy.scale(scale);
  42831. };
  42832. /**
  42833. * Gets the spherical polynomial from harmonics
  42834. * @param harmonics the spherical harmonics
  42835. * @returns the spherical polynomial
  42836. */
  42837. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42838. var result = new SphericalPolynomial();
  42839. result.x = harmonics.l11.scale(1.02333);
  42840. result.y = harmonics.l1_1.scale(1.02333);
  42841. result.z = harmonics.l10.scale(1.02333);
  42842. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42843. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42844. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42845. result.yz = harmonics.l2_1.scale(0.858086);
  42846. result.zx = harmonics.l21.scale(0.858086);
  42847. result.xy = harmonics.l2_2.scale(0.858086);
  42848. result.scale(1.0 / Math.PI);
  42849. return result;
  42850. };
  42851. /**
  42852. * Constructs a spherical polynomial from an array.
  42853. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42854. * @returns the spherical polynomial
  42855. */
  42856. SphericalPolynomial.FromArray = function (data) {
  42857. var sp = new SphericalPolynomial();
  42858. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42859. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42860. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42861. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42862. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42863. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42864. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42865. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42866. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42867. return sp;
  42868. };
  42869. return SphericalPolynomial;
  42870. }());
  42871. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42872. /**
  42873. * Class representing spherical harmonics coefficients to the 3rd degree
  42874. */
  42875. var SphericalHarmonics = /** @class */ (function () {
  42876. function SphericalHarmonics() {
  42877. /**
  42878. * The l0,0 coefficients of the spherical harmonics
  42879. */
  42880. this.l00 = BABYLON.Vector3.Zero();
  42881. /**
  42882. * The l1,-1 coefficients of the spherical harmonics
  42883. */
  42884. this.l1_1 = BABYLON.Vector3.Zero();
  42885. /**
  42886. * The l1,0 coefficients of the spherical harmonics
  42887. */
  42888. this.l10 = BABYLON.Vector3.Zero();
  42889. /**
  42890. * The l1,1 coefficients of the spherical harmonics
  42891. */
  42892. this.l11 = BABYLON.Vector3.Zero();
  42893. /**
  42894. * The l2,-2 coefficients of the spherical harmonics
  42895. */
  42896. this.l2_2 = BABYLON.Vector3.Zero();
  42897. /**
  42898. * The l2,-1 coefficients of the spherical harmonics
  42899. */
  42900. this.l2_1 = BABYLON.Vector3.Zero();
  42901. /**
  42902. * The l2,0 coefficients of the spherical harmonics
  42903. */
  42904. this.l20 = BABYLON.Vector3.Zero();
  42905. /**
  42906. * The l2,1 coefficients of the spherical harmonics
  42907. */
  42908. this.l21 = BABYLON.Vector3.Zero();
  42909. /**
  42910. * The l2,2 coefficients of the spherical harmonics
  42911. */
  42912. this.lL22 = BABYLON.Vector3.Zero();
  42913. }
  42914. /**
  42915. * Adds a light to the spherical harmonics
  42916. * @param direction the direction of the light
  42917. * @param color the color of the light
  42918. * @param deltaSolidAngle the delta solid angle of the light
  42919. */
  42920. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  42921. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42922. var c = colorVector.scale(deltaSolidAngle);
  42923. this.l00 = this.l00.add(c.scale(0.282095));
  42924. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  42925. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  42926. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  42927. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  42928. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  42929. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  42930. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  42931. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  42932. };
  42933. /**
  42934. * Scales the spherical harmonics by the given amount
  42935. * @param scale the amount to scale
  42936. */
  42937. SphericalHarmonics.prototype.scale = function (scale) {
  42938. this.l00 = this.l00.scale(scale);
  42939. this.l1_1 = this.l1_1.scale(scale);
  42940. this.l10 = this.l10.scale(scale);
  42941. this.l11 = this.l11.scale(scale);
  42942. this.l2_2 = this.l2_2.scale(scale);
  42943. this.l2_1 = this.l2_1.scale(scale);
  42944. this.l20 = this.l20.scale(scale);
  42945. this.l21 = this.l21.scale(scale);
  42946. this.lL22 = this.lL22.scale(scale);
  42947. };
  42948. /**
  42949. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  42950. *
  42951. * ```
  42952. * E_lm = A_l * L_lm
  42953. * ```
  42954. *
  42955. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  42956. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  42957. * the scaling factors are given in equation 9.
  42958. */
  42959. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  42960. // Constant (Band 0)
  42961. this.l00 = this.l00.scale(3.141593);
  42962. // Linear (Band 1)
  42963. this.l1_1 = this.l1_1.scale(2.094395);
  42964. this.l10 = this.l10.scale(2.094395);
  42965. this.l11 = this.l11.scale(2.094395);
  42966. // Quadratic (Band 2)
  42967. this.l2_2 = this.l2_2.scale(0.785398);
  42968. this.l2_1 = this.l2_1.scale(0.785398);
  42969. this.l20 = this.l20.scale(0.785398);
  42970. this.l21 = this.l21.scale(0.785398);
  42971. this.lL22 = this.lL22.scale(0.785398);
  42972. };
  42973. /**
  42974. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  42975. *
  42976. * ```
  42977. * L = (1/pi) * E * rho
  42978. * ```
  42979. *
  42980. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  42981. */
  42982. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  42983. this.scale(1.0 / Math.PI);
  42984. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  42985. // (The pixel shader must apply albedo after texture fetches, etc).
  42986. };
  42987. /**
  42988. * Gets the spherical harmonics from polynomial
  42989. * @param polynomial the spherical polynomial
  42990. * @returns the spherical harmonics
  42991. */
  42992. SphericalHarmonics.FromPolynomial = function (polynomial) {
  42993. var result = new SphericalHarmonics();
  42994. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  42995. result.l1_1 = polynomial.y.scale(0.977204);
  42996. result.l10 = polynomial.z.scale(0.977204);
  42997. result.l11 = polynomial.x.scale(0.977204);
  42998. result.l2_2 = polynomial.xy.scale(1.16538);
  42999. result.l2_1 = polynomial.yz.scale(1.16538);
  43000. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43001. result.l21 = polynomial.zx.scale(1.16538);
  43002. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43003. result.scale(Math.PI);
  43004. return result;
  43005. };
  43006. /**
  43007. * Constructs a spherical harmonics from an array.
  43008. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43009. * @returns the spherical harmonics
  43010. */
  43011. SphericalHarmonics.FromArray = function (data) {
  43012. var sh = new SphericalHarmonics();
  43013. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43014. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43015. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43016. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43017. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43018. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43019. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43020. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43021. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43022. return sh;
  43023. };
  43024. return SphericalHarmonics;
  43025. }());
  43026. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43027. })(BABYLON || (BABYLON = {}));
  43028. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43029. var BABYLON;
  43030. (function (BABYLON) {
  43031. var FileFaceOrientation = /** @class */ (function () {
  43032. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43033. this.name = name;
  43034. this.worldAxisForNormal = worldAxisForNormal;
  43035. this.worldAxisForFileX = worldAxisForFileX;
  43036. this.worldAxisForFileY = worldAxisForFileY;
  43037. }
  43038. return FileFaceOrientation;
  43039. }());
  43040. ;
  43041. /**
  43042. * Helper class dealing with the extraction of spherical polynomial dataArray
  43043. * from a cube map.
  43044. */
  43045. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43046. function CubeMapToSphericalPolynomialTools() {
  43047. }
  43048. /**
  43049. * Converts a texture to the according Spherical Polynomial data.
  43050. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43051. *
  43052. * @param texture The texture to extract the information from.
  43053. * @return The Spherical Polynomial data.
  43054. */
  43055. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43056. if (!texture.isCube) {
  43057. // Only supports cube Textures currently.
  43058. return null;
  43059. }
  43060. var size = texture.getSize().width;
  43061. var right = texture.readPixels(0);
  43062. var left = texture.readPixels(1);
  43063. var up;
  43064. var down;
  43065. if (texture.isRenderTarget) {
  43066. up = texture.readPixels(3);
  43067. down = texture.readPixels(2);
  43068. }
  43069. else {
  43070. up = texture.readPixels(2);
  43071. down = texture.readPixels(3);
  43072. }
  43073. var front = texture.readPixels(4);
  43074. var back = texture.readPixels(5);
  43075. var gammaSpace = texture.gammaSpace;
  43076. // Always read as RGBA.
  43077. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43078. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43079. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43080. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43081. }
  43082. var cubeInfo = {
  43083. size: size,
  43084. right: right,
  43085. left: left,
  43086. up: up,
  43087. down: down,
  43088. front: front,
  43089. back: back,
  43090. format: format,
  43091. type: type,
  43092. gammaSpace: gammaSpace,
  43093. };
  43094. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43095. };
  43096. /**
  43097. * Converts a cubemap to the according Spherical Polynomial data.
  43098. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43099. *
  43100. * @param cubeInfo The Cube map to extract the information from.
  43101. * @return The Spherical Polynomial data.
  43102. */
  43103. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43104. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43105. var totalSolidAngle = 0.0;
  43106. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43107. var du = 2.0 / cubeInfo.size;
  43108. var dv = du;
  43109. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43110. var minUV = du * 0.5 - 1.0;
  43111. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43112. var fileFace = this.FileFaces[faceIndex];
  43113. var dataArray = cubeInfo[fileFace.name];
  43114. var v = minUV;
  43115. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43116. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43117. // Because SP is still linear, so summation is fine in that basis.
  43118. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43119. for (var y = 0; y < cubeInfo.size; y++) {
  43120. var u = minUV;
  43121. for (var x = 0; x < cubeInfo.size; x++) {
  43122. // World direction (not normalised)
  43123. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43124. worldDirection.normalize();
  43125. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43126. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43127. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43128. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43129. // Handle Integer types.
  43130. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43131. r /= 255;
  43132. g /= 255;
  43133. b /= 255;
  43134. }
  43135. // Handle Gamma space textures.
  43136. if (cubeInfo.gammaSpace) {
  43137. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43138. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43139. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43140. }
  43141. var color = new BABYLON.Color3(r, g, b);
  43142. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43143. totalSolidAngle += deltaSolidAngle;
  43144. u += du;
  43145. }
  43146. v += dv;
  43147. }
  43148. }
  43149. // Solid angle for entire sphere is 4*pi
  43150. var sphereSolidAngle = 4.0 * Math.PI;
  43151. // Adjust the solid angle to allow for how many faces we processed.
  43152. var facesProcessed = 6.0;
  43153. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43154. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43155. // This is needed because the numerical integration over the cube uses a
  43156. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43157. // and also to compensate for accumulative error due to float precision in the summation.
  43158. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43159. sphericalHarmonics.scale(correctionFactor);
  43160. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43161. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43162. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43163. };
  43164. CubeMapToSphericalPolynomialTools.FileFaces = [
  43165. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43166. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43167. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43168. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43169. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43170. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43171. ];
  43172. return CubeMapToSphericalPolynomialTools;
  43173. }());
  43174. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43175. })(BABYLON || (BABYLON = {}));
  43176. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43177. var BABYLON;
  43178. (function (BABYLON) {
  43179. /**
  43180. * Manages the defines for the PBR Material.
  43181. * @hiddenChildren
  43182. */
  43183. var PBRMaterialDefines = /** @class */ (function (_super) {
  43184. __extends(PBRMaterialDefines, _super);
  43185. /**
  43186. * Initializes the PBR Material defines.
  43187. */
  43188. function PBRMaterialDefines() {
  43189. var _this = _super.call(this) || this;
  43190. _this.PBR = true;
  43191. _this.MAINUV1 = false;
  43192. _this.MAINUV2 = false;
  43193. _this.UV1 = false;
  43194. _this.UV2 = false;
  43195. _this.ALBEDO = false;
  43196. _this.ALBEDODIRECTUV = 0;
  43197. _this.VERTEXCOLOR = false;
  43198. _this.AMBIENT = false;
  43199. _this.AMBIENTDIRECTUV = 0;
  43200. _this.AMBIENTINGRAYSCALE = false;
  43201. _this.OPACITY = false;
  43202. _this.VERTEXALPHA = false;
  43203. _this.OPACITYDIRECTUV = 0;
  43204. _this.OPACITYRGB = false;
  43205. _this.ALPHATEST = false;
  43206. _this.DEPTHPREPASS = false;
  43207. _this.ALPHABLEND = false;
  43208. _this.ALPHAFROMALBEDO = false;
  43209. _this.ALPHATESTVALUE = "0.5";
  43210. _this.SPECULAROVERALPHA = false;
  43211. _this.RADIANCEOVERALPHA = false;
  43212. _this.ALPHAFRESNEL = false;
  43213. _this.LINEARALPHAFRESNEL = false;
  43214. _this.PREMULTIPLYALPHA = false;
  43215. _this.EMISSIVE = false;
  43216. _this.EMISSIVEDIRECTUV = 0;
  43217. _this.REFLECTIVITY = false;
  43218. _this.REFLECTIVITYDIRECTUV = 0;
  43219. _this.SPECULARTERM = false;
  43220. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43221. _this.MICROSURFACEAUTOMATIC = false;
  43222. _this.LODBASEDMICROSFURACE = false;
  43223. _this.MICROSURFACEMAP = false;
  43224. _this.MICROSURFACEMAPDIRECTUV = 0;
  43225. _this.METALLICWORKFLOW = false;
  43226. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43227. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43228. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43229. _this.AOSTOREINMETALMAPRED = false;
  43230. _this.ENVIRONMENTBRDF = false;
  43231. _this.NORMAL = false;
  43232. _this.TANGENT = false;
  43233. _this.BUMP = false;
  43234. _this.BUMPDIRECTUV = 0;
  43235. _this.OBJECTSPACE_NORMALMAP = false;
  43236. _this.PARALLAX = false;
  43237. _this.PARALLAXOCCLUSION = false;
  43238. _this.NORMALXYSCALE = true;
  43239. _this.LIGHTMAP = false;
  43240. _this.LIGHTMAPDIRECTUV = 0;
  43241. _this.USELIGHTMAPASSHADOWMAP = false;
  43242. _this.GAMMALIGHTMAP = false;
  43243. _this.REFLECTION = false;
  43244. _this.REFLECTIONMAP_3D = false;
  43245. _this.REFLECTIONMAP_SPHERICAL = false;
  43246. _this.REFLECTIONMAP_PLANAR = false;
  43247. _this.REFLECTIONMAP_CUBIC = false;
  43248. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43249. _this.REFLECTIONMAP_PROJECTION = false;
  43250. _this.REFLECTIONMAP_SKYBOX = false;
  43251. _this.REFLECTIONMAP_EXPLICIT = false;
  43252. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43253. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43254. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43255. _this.INVERTCUBICMAP = false;
  43256. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43257. _this.USESPHERICALINVERTEX = false;
  43258. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43259. _this.LODINREFLECTIONALPHA = false;
  43260. _this.GAMMAREFLECTION = false;
  43261. _this.RGBDREFLECTION = false;
  43262. _this.RADIANCEOCCLUSION = false;
  43263. _this.HORIZONOCCLUSION = false;
  43264. _this.REFRACTION = false;
  43265. _this.REFRACTIONMAP_3D = false;
  43266. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43267. _this.LODINREFRACTIONALPHA = false;
  43268. _this.GAMMAREFRACTION = false;
  43269. _this.RGBDREFRACTION = false;
  43270. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43271. _this.INSTANCES = false;
  43272. _this.NUM_BONE_INFLUENCERS = 0;
  43273. _this.BonesPerMesh = 0;
  43274. _this.NONUNIFORMSCALING = false;
  43275. _this.MORPHTARGETS = false;
  43276. _this.MORPHTARGETS_NORMAL = false;
  43277. _this.MORPHTARGETS_TANGENT = false;
  43278. _this.NUM_MORPH_INFLUENCERS = 0;
  43279. _this.IMAGEPROCESSING = false;
  43280. _this.VIGNETTE = false;
  43281. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43282. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43283. _this.TONEMAPPING = false;
  43284. _this.CONTRAST = false;
  43285. _this.COLORCURVES = false;
  43286. _this.COLORGRADING = false;
  43287. _this.COLORGRADING3D = false;
  43288. _this.SAMPLER3DGREENDEPTH = false;
  43289. _this.SAMPLER3DBGRMAP = false;
  43290. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43291. _this.EXPOSURE = false;
  43292. _this.USEPHYSICALLIGHTFALLOFF = false;
  43293. _this.TWOSIDEDLIGHTING = false;
  43294. _this.SHADOWFLOAT = false;
  43295. _this.CLIPPLANE = false;
  43296. _this.POINTSIZE = false;
  43297. _this.FOG = false;
  43298. _this.LOGARITHMICDEPTH = false;
  43299. _this.FORCENORMALFORWARD = false;
  43300. _this.SPECULARAA = false;
  43301. _this.UNLIT = false;
  43302. _this.rebuild();
  43303. return _this;
  43304. }
  43305. /**
  43306. * Resets the PBR Material defines.
  43307. */
  43308. PBRMaterialDefines.prototype.reset = function () {
  43309. _super.prototype.reset.call(this);
  43310. this.ALPHATESTVALUE = "0.5";
  43311. this.PBR = true;
  43312. };
  43313. return PBRMaterialDefines;
  43314. }(BABYLON.MaterialDefines));
  43315. /**
  43316. * The Physically based material base class of BJS.
  43317. *
  43318. * This offers the main features of a standard PBR material.
  43319. * For more information, please refer to the documentation :
  43320. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43321. */
  43322. var PBRBaseMaterial = /** @class */ (function (_super) {
  43323. __extends(PBRBaseMaterial, _super);
  43324. /**
  43325. * Instantiates a new PBRMaterial instance.
  43326. *
  43327. * @param name The material name
  43328. * @param scene The scene the material will be use in.
  43329. */
  43330. function PBRBaseMaterial(name, scene) {
  43331. var _this = _super.call(this, name, scene) || this;
  43332. /**
  43333. * Intensity of the direct lights e.g. the four lights available in your scene.
  43334. * This impacts both the direct diffuse and specular highlights.
  43335. */
  43336. _this._directIntensity = 1.0;
  43337. /**
  43338. * Intensity of the emissive part of the material.
  43339. * This helps controlling the emissive effect without modifying the emissive color.
  43340. */
  43341. _this._emissiveIntensity = 1.0;
  43342. /**
  43343. * Intensity of the environment e.g. how much the environment will light the object
  43344. * either through harmonics for rough material or through the refelction for shiny ones.
  43345. */
  43346. _this._environmentIntensity = 1.0;
  43347. /**
  43348. * This is a special control allowing the reduction of the specular highlights coming from the
  43349. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43350. */
  43351. _this._specularIntensity = 1.0;
  43352. /**
  43353. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43354. */
  43355. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43356. /**
  43357. * Debug Control allowing disabling the bump map on this material.
  43358. */
  43359. _this._disableBumpMap = false;
  43360. /**
  43361. * AKA Occlusion Texture Intensity in other nomenclature.
  43362. */
  43363. _this._ambientTextureStrength = 1.0;
  43364. /**
  43365. * The color of a material in ambient lighting.
  43366. */
  43367. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43368. /**
  43369. * AKA Diffuse Color in other nomenclature.
  43370. */
  43371. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43372. /**
  43373. * AKA Specular Color in other nomenclature.
  43374. */
  43375. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43376. /**
  43377. * The color applied when light is reflected from a material.
  43378. */
  43379. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43380. /**
  43381. * The color applied when light is emitted from a material.
  43382. */
  43383. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43384. /**
  43385. * AKA Glossiness in other nomenclature.
  43386. */
  43387. _this._microSurface = 0.9;
  43388. /**
  43389. * source material index of refraction (IOR)' / 'destination material IOR.
  43390. */
  43391. _this._indexOfRefraction = 0.66;
  43392. /**
  43393. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43394. */
  43395. _this._invertRefractionY = false;
  43396. /**
  43397. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43398. * Materials half opaque for instance using refraction could benefit from this control.
  43399. */
  43400. _this._linkRefractionWithTransparency = false;
  43401. /**
  43402. * Specifies that the material will use the light map as a show map.
  43403. */
  43404. _this._useLightmapAsShadowmap = false;
  43405. /**
  43406. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43407. * makes the reflect vector face the model (under horizon).
  43408. */
  43409. _this._useHorizonOcclusion = true;
  43410. /**
  43411. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43412. * too much the area relying on ambient texture to define their ambient occlusion.
  43413. */
  43414. _this._useRadianceOcclusion = true;
  43415. /**
  43416. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43417. */
  43418. _this._useAlphaFromAlbedoTexture = false;
  43419. /**
  43420. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43421. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43422. */
  43423. _this._useSpecularOverAlpha = true;
  43424. /**
  43425. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43426. */
  43427. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43428. /**
  43429. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43430. */
  43431. _this._useRoughnessFromMetallicTextureAlpha = true;
  43432. /**
  43433. * Specifies if the metallic texture contains the roughness information in its green channel.
  43434. */
  43435. _this._useRoughnessFromMetallicTextureGreen = false;
  43436. /**
  43437. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43438. */
  43439. _this._useMetallnessFromMetallicTextureBlue = false;
  43440. /**
  43441. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43442. */
  43443. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43444. /**
  43445. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43446. */
  43447. _this._useAmbientInGrayScale = false;
  43448. /**
  43449. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43450. * The material will try to infer what glossiness each pixel should be.
  43451. */
  43452. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43453. /**
  43454. * BJS is using an harcoded light falloff based on a manually sets up range.
  43455. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43456. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43457. */
  43458. _this._usePhysicalLightFalloff = true;
  43459. /**
  43460. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43461. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43462. */
  43463. _this._useRadianceOverAlpha = true;
  43464. /**
  43465. * Allows using an object space normal map (instead of tangent space).
  43466. */
  43467. _this._useObjectSpaceNormalMap = false;
  43468. /**
  43469. * Allows using the bump map in parallax mode.
  43470. */
  43471. _this._useParallax = false;
  43472. /**
  43473. * Allows using the bump map in parallax occlusion mode.
  43474. */
  43475. _this._useParallaxOcclusion = false;
  43476. /**
  43477. * Controls the scale bias of the parallax mode.
  43478. */
  43479. _this._parallaxScaleBias = 0.05;
  43480. /**
  43481. * If sets to true, disables all the lights affecting the material.
  43482. */
  43483. _this._disableLighting = false;
  43484. /**
  43485. * Number of Simultaneous lights allowed on the material.
  43486. */
  43487. _this._maxSimultaneousLights = 4;
  43488. /**
  43489. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43490. */
  43491. _this._invertNormalMapX = false;
  43492. /**
  43493. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43494. */
  43495. _this._invertNormalMapY = false;
  43496. /**
  43497. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43498. */
  43499. _this._twoSidedLighting = false;
  43500. /**
  43501. * Defines the alpha limits in alpha test mode.
  43502. */
  43503. _this._alphaCutOff = 0.4;
  43504. /**
  43505. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43506. */
  43507. _this._forceAlphaTest = false;
  43508. /**
  43509. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43510. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43511. */
  43512. _this._useAlphaFresnel = false;
  43513. /**
  43514. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43515. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43516. */
  43517. _this._useLinearAlphaFresnel = false;
  43518. /**
  43519. * The transparency mode of the material.
  43520. */
  43521. _this._transparencyMode = null;
  43522. /**
  43523. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43524. * from cos thetav and roughness:
  43525. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43526. */
  43527. _this._environmentBRDFTexture = null;
  43528. /**
  43529. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43530. */
  43531. _this._forceIrradianceInFragment = false;
  43532. /**
  43533. * Force normal to face away from face.
  43534. */
  43535. _this._forceNormalForward = false;
  43536. /**
  43537. * Enables specular anti aliasing in the PBR shader.
  43538. * It will both interacts on the Geometry for analytical and IBL lighting.
  43539. * It also prefilter the roughness map based on the bump values.
  43540. */
  43541. _this._enableSpecularAntiAliasing = false;
  43542. /**
  43543. * Stores the available render targets.
  43544. */
  43545. _this._renderTargets = new BABYLON.SmartArray(16);
  43546. /**
  43547. * Sets the global ambient color for the material used in lighting calculations.
  43548. */
  43549. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43550. /**
  43551. * If set to true, no lighting calculations will be applied.
  43552. */
  43553. _this._unlit = false;
  43554. // Setup the default processing configuration to the scene.
  43555. _this._attachImageProcessingConfiguration(null);
  43556. _this.getRenderTargetTextures = function () {
  43557. _this._renderTargets.reset();
  43558. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43559. _this._renderTargets.push(_this._reflectionTexture);
  43560. }
  43561. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43562. _this._renderTargets.push(_this._refractionTexture);
  43563. }
  43564. return _this._renderTargets;
  43565. };
  43566. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43567. return _this;
  43568. }
  43569. /**
  43570. * Attaches a new image processing configuration to the PBR Material.
  43571. * @param configuration
  43572. */
  43573. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43574. var _this = this;
  43575. if (configuration === this._imageProcessingConfiguration) {
  43576. return;
  43577. }
  43578. // Detaches observer.
  43579. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43580. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43581. }
  43582. // Pick the scene configuration if needed.
  43583. if (!configuration) {
  43584. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43585. }
  43586. else {
  43587. this._imageProcessingConfiguration = configuration;
  43588. }
  43589. // Attaches observer.
  43590. if (this._imageProcessingConfiguration) {
  43591. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43592. _this._markAllSubMeshesAsImageProcessingDirty();
  43593. });
  43594. }
  43595. };
  43596. /**
  43597. * Gets the name of the material class.
  43598. */
  43599. PBRBaseMaterial.prototype.getClassName = function () {
  43600. return "PBRBaseMaterial";
  43601. };
  43602. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43603. /**
  43604. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43605. */
  43606. get: function () {
  43607. return this._useLogarithmicDepth;
  43608. },
  43609. /**
  43610. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43611. */
  43612. set: function (value) {
  43613. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43614. },
  43615. enumerable: true,
  43616. configurable: true
  43617. });
  43618. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43619. /**
  43620. * Gets the current transparency mode.
  43621. */
  43622. get: function () {
  43623. return this._transparencyMode;
  43624. },
  43625. /**
  43626. * Sets the transparency mode of the material.
  43627. *
  43628. * | Value | Type | Description |
  43629. * | ----- | ----------------------------------- | ----------- |
  43630. * | 0 | OPAQUE | |
  43631. * | 1 | ALPHATEST | |
  43632. * | 2 | ALPHABLEND | |
  43633. * | 3 | ALPHATESTANDBLEND | |
  43634. *
  43635. */
  43636. set: function (value) {
  43637. if (this._transparencyMode === value) {
  43638. return;
  43639. }
  43640. this._transparencyMode = value;
  43641. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43642. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43643. },
  43644. enumerable: true,
  43645. configurable: true
  43646. });
  43647. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43648. /**
  43649. * Returns true if alpha blending should be disabled.
  43650. */
  43651. get: function () {
  43652. return (this._linkRefractionWithTransparency ||
  43653. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43654. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43655. },
  43656. enumerable: true,
  43657. configurable: true
  43658. });
  43659. /**
  43660. * Specifies whether or not this material should be rendered in alpha blend mode.
  43661. */
  43662. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43663. if (this._disableAlphaBlending) {
  43664. return false;
  43665. }
  43666. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43667. };
  43668. /**
  43669. * Specifies if the mesh will require alpha blending.
  43670. * @param mesh - BJS mesh.
  43671. */
  43672. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43673. if (this._disableAlphaBlending) {
  43674. return false;
  43675. }
  43676. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43677. };
  43678. /**
  43679. * Specifies whether or not this material should be rendered in alpha test mode.
  43680. */
  43681. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43682. if (this._forceAlphaTest) {
  43683. return true;
  43684. }
  43685. if (this._linkRefractionWithTransparency) {
  43686. return false;
  43687. }
  43688. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43689. };
  43690. /**
  43691. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43692. */
  43693. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43694. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43695. };
  43696. /**
  43697. * Gets the texture used for the alpha test.
  43698. */
  43699. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43700. return this._albedoTexture;
  43701. };
  43702. /**
  43703. * Specifies that the submesh is ready to be used.
  43704. * @param mesh - BJS mesh.
  43705. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43706. * @param useInstances - Specifies that instances should be used.
  43707. * @returns - boolean indicating that the submesh is ready or not.
  43708. */
  43709. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43710. if (subMesh.effect && this.isFrozen) {
  43711. if (this._wasPreviouslyReady) {
  43712. return true;
  43713. }
  43714. }
  43715. if (!subMesh._materialDefines) {
  43716. subMesh._materialDefines = new PBRMaterialDefines();
  43717. }
  43718. var defines = subMesh._materialDefines;
  43719. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43720. if (defines._renderId === this.getScene().getRenderId()) {
  43721. return true;
  43722. }
  43723. }
  43724. var scene = this.getScene();
  43725. var engine = scene.getEngine();
  43726. if (defines._areTexturesDirty) {
  43727. if (scene.texturesEnabled) {
  43728. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43729. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43730. return false;
  43731. }
  43732. }
  43733. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43734. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43735. return false;
  43736. }
  43737. }
  43738. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43739. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43740. return false;
  43741. }
  43742. }
  43743. var reflectionTexture = this._getReflectionTexture();
  43744. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43745. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43746. return false;
  43747. }
  43748. }
  43749. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43750. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43751. return false;
  43752. }
  43753. }
  43754. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43755. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43756. return false;
  43757. }
  43758. }
  43759. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43760. if (this._metallicTexture) {
  43761. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43762. return false;
  43763. }
  43764. }
  43765. else if (this._reflectivityTexture) {
  43766. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43767. return false;
  43768. }
  43769. }
  43770. if (this._microSurfaceTexture) {
  43771. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43772. return false;
  43773. }
  43774. }
  43775. }
  43776. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43777. // Bump texture cannot be not blocking.
  43778. if (!this._bumpTexture.isReady()) {
  43779. return false;
  43780. }
  43781. }
  43782. var refractionTexture = this._getRefractionTexture();
  43783. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43784. if (!refractionTexture.isReadyOrNotBlocking()) {
  43785. return false;
  43786. }
  43787. }
  43788. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43789. // This is blocking.
  43790. if (!this._environmentBRDFTexture.isReady()) {
  43791. return false;
  43792. }
  43793. }
  43794. }
  43795. }
  43796. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43797. if (!this._imageProcessingConfiguration.isReady()) {
  43798. return false;
  43799. }
  43800. }
  43801. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43802. mesh.createNormals(true);
  43803. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43804. }
  43805. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43806. if (effect) {
  43807. scene.resetCachedMaterial();
  43808. subMesh.setEffect(effect, defines);
  43809. this.buildUniformLayout();
  43810. }
  43811. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43812. return false;
  43813. }
  43814. defines._renderId = scene.getRenderId();
  43815. this._wasPreviouslyReady = true;
  43816. return true;
  43817. };
  43818. /**
  43819. * Specifies if the material uses metallic roughness workflow.
  43820. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43821. */
  43822. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43823. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43824. return true;
  43825. }
  43826. return false;
  43827. };
  43828. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43829. if (onCompiled === void 0) { onCompiled = null; }
  43830. if (onError === void 0) { onError = null; }
  43831. if (useInstances === void 0) { useInstances = null; }
  43832. if (useClipPlane === void 0) { useClipPlane = null; }
  43833. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43834. if (!defines.isDirty) {
  43835. return null;
  43836. }
  43837. defines.markAsProcessed();
  43838. var scene = this.getScene();
  43839. var engine = scene.getEngine();
  43840. // Fallbacks
  43841. var fallbacks = new BABYLON.EffectFallbacks();
  43842. var fallbackRank = 0;
  43843. if (defines.USESPHERICALINVERTEX) {
  43844. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43845. }
  43846. if (defines.FOG) {
  43847. fallbacks.addFallback(fallbackRank, "FOG");
  43848. }
  43849. if (defines.SPECULARAA) {
  43850. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43851. }
  43852. if (defines.POINTSIZE) {
  43853. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43854. }
  43855. if (defines.LOGARITHMICDEPTH) {
  43856. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43857. }
  43858. if (defines.PARALLAX) {
  43859. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43860. }
  43861. if (defines.PARALLAXOCCLUSION) {
  43862. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43863. }
  43864. if (defines.ENVIRONMENTBRDF) {
  43865. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43866. }
  43867. if (defines.TANGENT) {
  43868. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43869. }
  43870. if (defines.BUMP) {
  43871. fallbacks.addFallback(fallbackRank++, "BUMP");
  43872. }
  43873. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43874. if (defines.SPECULARTERM) {
  43875. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43876. }
  43877. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43878. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43879. }
  43880. if (defines.LIGHTMAP) {
  43881. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43882. }
  43883. if (defines.NORMAL) {
  43884. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43885. }
  43886. if (defines.AMBIENT) {
  43887. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43888. }
  43889. if (defines.EMISSIVE) {
  43890. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43891. }
  43892. if (defines.VERTEXCOLOR) {
  43893. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43894. }
  43895. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43896. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43897. }
  43898. if (defines.MORPHTARGETS) {
  43899. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43900. }
  43901. //Attributes
  43902. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43903. if (defines.NORMAL) {
  43904. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43905. }
  43906. if (defines.TANGENT) {
  43907. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43908. }
  43909. if (defines.UV1) {
  43910. attribs.push(BABYLON.VertexBuffer.UVKind);
  43911. }
  43912. if (defines.UV2) {
  43913. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43914. }
  43915. if (defines.VERTEXCOLOR) {
  43916. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43917. }
  43918. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43919. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43920. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43921. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43922. "vFogInfos", "vFogColor", "pointSize",
  43923. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43924. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43925. "mBones",
  43926. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43927. "vLightingIntensity",
  43928. "logarithmicDepthConstant",
  43929. "vSphericalX", "vSphericalY", "vSphericalZ",
  43930. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43931. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43932. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43933. "vTangentSpaceParams"
  43934. ];
  43935. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43936. "bumpSampler", "lightmapSampler", "opacitySampler",
  43937. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43938. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43939. "microSurfaceSampler", "environmentBrdfSampler"];
  43940. var uniformBuffers = ["Material", "Scene"];
  43941. if (BABYLON.ImageProcessingConfiguration) {
  43942. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43943. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43944. }
  43945. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43946. uniformsNames: uniforms,
  43947. uniformBuffersNames: uniformBuffers,
  43948. samplers: samplers,
  43949. defines: defines,
  43950. maxSimultaneousLights: this._maxSimultaneousLights
  43951. });
  43952. var join = defines.toString();
  43953. return engine.createEffect("pbr", {
  43954. attributes: attribs,
  43955. uniformsNames: uniforms,
  43956. uniformBuffersNames: uniformBuffers,
  43957. samplers: samplers,
  43958. defines: join,
  43959. fallbacks: fallbacks,
  43960. onCompiled: onCompiled,
  43961. onError: onError,
  43962. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43963. }, engine);
  43964. };
  43965. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43966. if (useInstances === void 0) { useInstances = null; }
  43967. if (useClipPlane === void 0) { useClipPlane = null; }
  43968. var scene = this.getScene();
  43969. var engine = scene.getEngine();
  43970. // Lights
  43971. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43972. defines._needNormals = true;
  43973. // Textures
  43974. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43975. if (defines._areTexturesDirty) {
  43976. defines._needUVs = false;
  43977. if (scene.texturesEnabled) {
  43978. if (scene.getEngine().getCaps().textureLOD) {
  43979. defines.LODBASEDMICROSFURACE = true;
  43980. }
  43981. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43982. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43983. }
  43984. else {
  43985. defines.ALBEDO = false;
  43986. }
  43987. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43988. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43989. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43990. }
  43991. else {
  43992. defines.AMBIENT = false;
  43993. }
  43994. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43995. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43996. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43997. }
  43998. else {
  43999. defines.OPACITY = false;
  44000. }
  44001. var reflectionTexture = this._getReflectionTexture();
  44002. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44003. defines.REFLECTION = true;
  44004. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44005. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44006. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44007. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44008. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44009. defines.INVERTCUBICMAP = true;
  44010. }
  44011. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44012. switch (reflectionTexture.coordinatesMode) {
  44013. case BABYLON.Texture.EXPLICIT_MODE:
  44014. defines.REFLECTIONMAP_EXPLICIT = true;
  44015. break;
  44016. case BABYLON.Texture.PLANAR_MODE:
  44017. defines.REFLECTIONMAP_PLANAR = true;
  44018. break;
  44019. case BABYLON.Texture.PROJECTION_MODE:
  44020. defines.REFLECTIONMAP_PROJECTION = true;
  44021. break;
  44022. case BABYLON.Texture.SKYBOX_MODE:
  44023. defines.REFLECTIONMAP_SKYBOX = true;
  44024. break;
  44025. case BABYLON.Texture.SPHERICAL_MODE:
  44026. defines.REFLECTIONMAP_SPHERICAL = true;
  44027. break;
  44028. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44029. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44030. break;
  44031. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44032. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44033. break;
  44034. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44035. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44036. break;
  44037. case BABYLON.Texture.CUBIC_MODE:
  44038. case BABYLON.Texture.INVCUBIC_MODE:
  44039. default:
  44040. defines.REFLECTIONMAP_CUBIC = true;
  44041. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44042. break;
  44043. }
  44044. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44045. if (reflectionTexture.sphericalPolynomial) {
  44046. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44047. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44048. defines.USESPHERICALINVERTEX = false;
  44049. }
  44050. else {
  44051. defines.USESPHERICALINVERTEX = true;
  44052. }
  44053. }
  44054. }
  44055. }
  44056. else {
  44057. defines.REFLECTION = false;
  44058. defines.REFLECTIONMAP_3D = false;
  44059. defines.REFLECTIONMAP_SPHERICAL = false;
  44060. defines.REFLECTIONMAP_PLANAR = false;
  44061. defines.REFLECTIONMAP_CUBIC = false;
  44062. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44063. defines.REFLECTIONMAP_PROJECTION = false;
  44064. defines.REFLECTIONMAP_SKYBOX = false;
  44065. defines.REFLECTIONMAP_EXPLICIT = false;
  44066. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44067. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44068. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44069. defines.INVERTCUBICMAP = false;
  44070. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44071. defines.USESPHERICALINVERTEX = false;
  44072. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44073. defines.LODINREFLECTIONALPHA = false;
  44074. defines.GAMMAREFLECTION = false;
  44075. defines.RGBDREFLECTION = false;
  44076. }
  44077. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44078. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44079. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44080. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44081. }
  44082. else {
  44083. defines.LIGHTMAP = false;
  44084. }
  44085. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44086. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44087. }
  44088. else {
  44089. defines.EMISSIVE = false;
  44090. }
  44091. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44092. if (this._metallicTexture) {
  44093. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44094. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44095. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44096. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44097. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44098. }
  44099. else if (this._reflectivityTexture) {
  44100. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44101. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44102. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44103. }
  44104. else {
  44105. defines.REFLECTIVITY = false;
  44106. }
  44107. if (this._microSurfaceTexture) {
  44108. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44109. }
  44110. else {
  44111. defines.MICROSURFACEMAP = false;
  44112. }
  44113. }
  44114. else {
  44115. defines.REFLECTIVITY = false;
  44116. defines.MICROSURFACEMAP = false;
  44117. }
  44118. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44119. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44120. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44121. defines.PARALLAX = true;
  44122. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44123. }
  44124. else {
  44125. defines.PARALLAX = false;
  44126. }
  44127. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44128. }
  44129. else {
  44130. defines.BUMP = false;
  44131. }
  44132. var refractionTexture = this._getRefractionTexture();
  44133. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44134. defines.REFRACTION = true;
  44135. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44136. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44137. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44138. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44139. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44140. if (this._linkRefractionWithTransparency) {
  44141. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44142. }
  44143. }
  44144. else {
  44145. defines.REFRACTION = false;
  44146. }
  44147. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44148. defines.ENVIRONMENTBRDF = true;
  44149. }
  44150. else {
  44151. defines.ENVIRONMENTBRDF = false;
  44152. }
  44153. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44154. defines.ALPHAFROMALBEDO = true;
  44155. }
  44156. else {
  44157. defines.ALPHAFROMALBEDO = false;
  44158. }
  44159. }
  44160. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44161. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44162. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44163. if (!this.backFaceCulling && this._twoSidedLighting) {
  44164. defines.TWOSIDEDLIGHTING = true;
  44165. }
  44166. else {
  44167. defines.TWOSIDEDLIGHTING = false;
  44168. }
  44169. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44170. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44171. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44172. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44173. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44174. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44175. }
  44176. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44177. this._imageProcessingConfiguration.prepareDefines(defines);
  44178. }
  44179. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44180. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44181. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44182. // Misc.
  44183. if (defines._areMiscDirty) {
  44184. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44185. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44186. }
  44187. // Values that need to be evaluated on every frame
  44188. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44189. // Attribs
  44190. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44191. };
  44192. /**
  44193. * Force shader compilation
  44194. */
  44195. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44196. var _this = this;
  44197. var localOptions = __assign({ clipPlane: false }, options);
  44198. var defines = new PBRMaterialDefines();
  44199. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44200. if (effect.isReady()) {
  44201. if (onCompiled) {
  44202. onCompiled(this);
  44203. }
  44204. }
  44205. else {
  44206. effect.onCompileObservable.add(function () {
  44207. if (onCompiled) {
  44208. onCompiled(_this);
  44209. }
  44210. });
  44211. }
  44212. };
  44213. /**
  44214. * Initializes the uniform buffer layout for the shader.
  44215. */
  44216. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44217. // Order is important !
  44218. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44219. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44220. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44221. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44222. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44223. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44224. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44225. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44226. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44227. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44228. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44229. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44230. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44231. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44232. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44233. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44234. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44235. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44236. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44237. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44238. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44239. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44240. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44241. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44242. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44243. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44244. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44245. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44246. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44247. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44248. this._uniformBuffer.addUniform("pointSize", 1);
  44249. this._uniformBuffer.create();
  44250. };
  44251. /**
  44252. * Unbinds the textures.
  44253. */
  44254. PBRBaseMaterial.prototype.unbind = function () {
  44255. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44256. this._uniformBuffer.setTexture("reflectionSampler", null);
  44257. }
  44258. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44259. this._uniformBuffer.setTexture("refractionSampler", null);
  44260. }
  44261. _super.prototype.unbind.call(this);
  44262. };
  44263. /**
  44264. * Binds the submesh data.
  44265. * @param world - The world matrix.
  44266. * @param mesh - The BJS mesh.
  44267. * @param subMesh - A submesh of the BJS mesh.
  44268. */
  44269. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44270. var scene = this.getScene();
  44271. var defines = subMesh._materialDefines;
  44272. if (!defines) {
  44273. return;
  44274. }
  44275. var effect = subMesh.effect;
  44276. if (!effect) {
  44277. return;
  44278. }
  44279. this._activeEffect = effect;
  44280. // Matrices
  44281. this.bindOnlyWorldMatrix(world);
  44282. // Normal Matrix
  44283. if (defines.OBJECTSPACE_NORMALMAP) {
  44284. world.toNormalMatrix(this._normalMatrix);
  44285. this.bindOnlyNormalMatrix(this._normalMatrix);
  44286. }
  44287. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44288. // Bones
  44289. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44290. var reflectionTexture = null;
  44291. if (mustRebind) {
  44292. this._uniformBuffer.bindToEffect(effect, "Material");
  44293. this.bindViewProjection(effect);
  44294. reflectionTexture = this._getReflectionTexture();
  44295. var refractionTexture = this._getRefractionTexture();
  44296. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44297. // Texture uniforms
  44298. if (scene.texturesEnabled) {
  44299. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44300. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44301. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44302. }
  44303. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44304. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44305. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44306. }
  44307. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44308. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44309. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44310. }
  44311. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44312. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44313. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44314. if (reflectionTexture.boundingBoxSize) {
  44315. var cubeTexture = reflectionTexture;
  44316. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44317. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44318. }
  44319. var polynomials = reflectionTexture.sphericalPolynomial;
  44320. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44321. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44322. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44323. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44324. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44325. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44326. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44327. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44328. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44329. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44330. }
  44331. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44332. }
  44333. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44334. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44335. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44336. }
  44337. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44338. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44339. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44340. }
  44341. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44342. if (this._metallicTexture) {
  44343. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44344. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44345. }
  44346. else if (this._reflectivityTexture) {
  44347. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44348. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44349. }
  44350. if (this._microSurfaceTexture) {
  44351. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44352. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44353. }
  44354. }
  44355. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44356. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44357. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44358. if (scene._mirroredCameraPosition) {
  44359. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44360. }
  44361. else {
  44362. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44363. }
  44364. }
  44365. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44366. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44367. var depth = 1.0;
  44368. if (!refractionTexture.isCube) {
  44369. if (refractionTexture.depth) {
  44370. depth = refractionTexture.depth;
  44371. }
  44372. }
  44373. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44374. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44375. }
  44376. }
  44377. // Point size
  44378. if (this.pointsCloud) {
  44379. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44380. }
  44381. // Colors
  44382. if (defines.METALLICWORKFLOW) {
  44383. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44384. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44385. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44386. }
  44387. else {
  44388. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44389. }
  44390. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44391. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44392. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44393. // Misc
  44394. this._lightingInfos.x = this._directIntensity;
  44395. this._lightingInfos.y = this._emissiveIntensity;
  44396. this._lightingInfos.z = this._environmentIntensity;
  44397. this._lightingInfos.w = this._specularIntensity;
  44398. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44399. }
  44400. // Textures
  44401. if (scene.texturesEnabled) {
  44402. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44403. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44404. }
  44405. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44406. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44407. }
  44408. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44409. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44410. }
  44411. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44412. if (defines.LODBASEDMICROSFURACE) {
  44413. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44414. }
  44415. else {
  44416. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44417. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44418. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44419. }
  44420. }
  44421. if (defines.ENVIRONMENTBRDF) {
  44422. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44423. }
  44424. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44425. if (defines.LODBASEDMICROSFURACE) {
  44426. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44427. }
  44428. else {
  44429. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44430. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44431. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44432. }
  44433. }
  44434. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44435. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44436. }
  44437. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44438. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44439. }
  44440. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44441. if (this._metallicTexture) {
  44442. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44443. }
  44444. else if (this._reflectivityTexture) {
  44445. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44446. }
  44447. if (this._microSurfaceTexture) {
  44448. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44449. }
  44450. }
  44451. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44452. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44453. }
  44454. }
  44455. // Clip plane
  44456. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44457. // Colors
  44458. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44459. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44460. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44461. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44462. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44463. }
  44464. if (mustRebind || !this.isFrozen) {
  44465. // Lights
  44466. if (scene.lightsEnabled && !this._disableLighting) {
  44467. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44468. }
  44469. // View
  44470. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44471. this.bindView(effect);
  44472. }
  44473. // Fog
  44474. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44475. // Morph targets
  44476. if (defines.NUM_MORPH_INFLUENCERS) {
  44477. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44478. }
  44479. // image processing
  44480. this._imageProcessingConfiguration.bind(this._activeEffect);
  44481. // Log. depth
  44482. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44483. }
  44484. this._uniformBuffer.update();
  44485. this._afterBind(mesh, this._activeEffect);
  44486. };
  44487. /**
  44488. * Returns the animatable textures.
  44489. * @returns - Array of animatable textures.
  44490. */
  44491. PBRBaseMaterial.prototype.getAnimatables = function () {
  44492. var results = [];
  44493. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44494. results.push(this._albedoTexture);
  44495. }
  44496. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44497. results.push(this._ambientTexture);
  44498. }
  44499. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44500. results.push(this._opacityTexture);
  44501. }
  44502. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44503. results.push(this._reflectionTexture);
  44504. }
  44505. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44506. results.push(this._emissiveTexture);
  44507. }
  44508. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44509. results.push(this._metallicTexture);
  44510. }
  44511. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44512. results.push(this._reflectivityTexture);
  44513. }
  44514. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44515. results.push(this._bumpTexture);
  44516. }
  44517. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44518. results.push(this._lightmapTexture);
  44519. }
  44520. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44521. results.push(this._refractionTexture);
  44522. }
  44523. return results;
  44524. };
  44525. /**
  44526. * Returns the texture used for reflections.
  44527. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44528. */
  44529. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44530. if (this._reflectionTexture) {
  44531. return this._reflectionTexture;
  44532. }
  44533. return this.getScene().environmentTexture;
  44534. };
  44535. /**
  44536. * Returns the texture used for refraction or null if none is used.
  44537. * @returns - Refection texture if present. If no refraction texture and refraction
  44538. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44539. */
  44540. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44541. if (this._refractionTexture) {
  44542. return this._refractionTexture;
  44543. }
  44544. if (this._linkRefractionWithTransparency) {
  44545. return this.getScene().environmentTexture;
  44546. }
  44547. return null;
  44548. };
  44549. /**
  44550. * Disposes the resources of the material.
  44551. * @param forceDisposeEffect - Forces the disposal of effects.
  44552. * @param forceDisposeTextures - Forces the disposal of all textures.
  44553. */
  44554. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44555. if (forceDisposeTextures) {
  44556. if (this._albedoTexture) {
  44557. this._albedoTexture.dispose();
  44558. }
  44559. if (this._ambientTexture) {
  44560. this._ambientTexture.dispose();
  44561. }
  44562. if (this._opacityTexture) {
  44563. this._opacityTexture.dispose();
  44564. }
  44565. if (this._reflectionTexture) {
  44566. this._reflectionTexture.dispose();
  44567. }
  44568. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44569. this._environmentBRDFTexture.dispose();
  44570. }
  44571. if (this._emissiveTexture) {
  44572. this._emissiveTexture.dispose();
  44573. }
  44574. if (this._metallicTexture) {
  44575. this._metallicTexture.dispose();
  44576. }
  44577. if (this._reflectivityTexture) {
  44578. this._reflectivityTexture.dispose();
  44579. }
  44580. if (this._bumpTexture) {
  44581. this._bumpTexture.dispose();
  44582. }
  44583. if (this._lightmapTexture) {
  44584. this._lightmapTexture.dispose();
  44585. }
  44586. if (this._refractionTexture) {
  44587. this._refractionTexture.dispose();
  44588. }
  44589. }
  44590. this._renderTargets.dispose();
  44591. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44592. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44593. }
  44594. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44595. };
  44596. /**
  44597. * Stores the reflectivity values based on metallic roughness workflow.
  44598. */
  44599. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44600. __decorate([
  44601. BABYLON.serializeAsImageProcessingConfiguration()
  44602. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44603. __decorate([
  44604. BABYLON.serialize()
  44605. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44606. __decorate([
  44607. BABYLON.serialize()
  44608. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44609. return PBRBaseMaterial;
  44610. }(BABYLON.PushMaterial));
  44611. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44612. })(BABYLON || (BABYLON = {}));
  44613. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44614. var BABYLON;
  44615. (function (BABYLON) {
  44616. /**
  44617. * The Physically based simple base material of BJS.
  44618. *
  44619. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44620. * It is used as the base class for both the specGloss and metalRough conventions.
  44621. */
  44622. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44623. __extends(PBRBaseSimpleMaterial, _super);
  44624. /**
  44625. * Instantiates a new PBRMaterial instance.
  44626. *
  44627. * @param name The material name
  44628. * @param scene The scene the material will be use in.
  44629. */
  44630. function PBRBaseSimpleMaterial(name, scene) {
  44631. var _this = _super.call(this, name, scene) || this;
  44632. /**
  44633. * Number of Simultaneous lights allowed on the material.
  44634. */
  44635. _this.maxSimultaneousLights = 4;
  44636. /**
  44637. * If sets to true, disables all the lights affecting the material.
  44638. */
  44639. _this.disableLighting = false;
  44640. /**
  44641. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44642. */
  44643. _this.invertNormalMapX = false;
  44644. /**
  44645. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44646. */
  44647. _this.invertNormalMapY = false;
  44648. /**
  44649. * Emissivie color used to self-illuminate the model.
  44650. */
  44651. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44652. /**
  44653. * Occlusion Channel Strenght.
  44654. */
  44655. _this.occlusionStrength = 1.0;
  44656. _this.useLightmapAsShadowmap = false;
  44657. _this._useAlphaFromAlbedoTexture = true;
  44658. _this._useAmbientInGrayScale = true;
  44659. return _this;
  44660. }
  44661. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44662. /**
  44663. * Gets the current double sided mode.
  44664. */
  44665. get: function () {
  44666. return this._twoSidedLighting;
  44667. },
  44668. /**
  44669. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44670. */
  44671. set: function (value) {
  44672. if (this._twoSidedLighting === value) {
  44673. return;
  44674. }
  44675. this._twoSidedLighting = value;
  44676. this.backFaceCulling = !value;
  44677. this._markAllSubMeshesAsTexturesDirty();
  44678. },
  44679. enumerable: true,
  44680. configurable: true
  44681. });
  44682. /**
  44683. * Return the active textures of the material.
  44684. */
  44685. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44686. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44687. if (this.environmentTexture) {
  44688. activeTextures.push(this.environmentTexture);
  44689. }
  44690. if (this.normalTexture) {
  44691. activeTextures.push(this.normalTexture);
  44692. }
  44693. if (this.emissiveTexture) {
  44694. activeTextures.push(this.emissiveTexture);
  44695. }
  44696. if (this.occlusionTexture) {
  44697. activeTextures.push(this.occlusionTexture);
  44698. }
  44699. if (this.lightmapTexture) {
  44700. activeTextures.push(this.lightmapTexture);
  44701. }
  44702. return activeTextures;
  44703. };
  44704. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44705. if (_super.prototype.hasTexture.call(this, texture)) {
  44706. return true;
  44707. }
  44708. if (this.lightmapTexture === texture) {
  44709. return true;
  44710. }
  44711. return false;
  44712. };
  44713. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44714. return "PBRBaseSimpleMaterial";
  44715. };
  44716. __decorate([
  44717. BABYLON.serialize(),
  44718. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44719. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44720. __decorate([
  44721. BABYLON.serialize(),
  44722. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44723. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44724. __decorate([
  44725. BABYLON.serializeAsTexture(),
  44726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44727. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44728. __decorate([
  44729. BABYLON.serialize(),
  44730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44731. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44732. __decorate([
  44733. BABYLON.serialize(),
  44734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44735. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44736. __decorate([
  44737. BABYLON.serializeAsTexture(),
  44738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44739. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44740. __decorate([
  44741. BABYLON.serializeAsColor3("emissive"),
  44742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44743. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44744. __decorate([
  44745. BABYLON.serializeAsTexture(),
  44746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44747. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44748. __decorate([
  44749. BABYLON.serialize(),
  44750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44751. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44752. __decorate([
  44753. BABYLON.serializeAsTexture(),
  44754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44755. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44756. __decorate([
  44757. BABYLON.serialize(),
  44758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44759. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44760. __decorate([
  44761. BABYLON.serialize()
  44762. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44763. __decorate([
  44764. BABYLON.serializeAsTexture(),
  44765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44766. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44767. __decorate([
  44768. BABYLON.serialize(),
  44769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44770. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44771. return PBRBaseSimpleMaterial;
  44772. }(BABYLON.PBRBaseMaterial));
  44773. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44774. })(BABYLON || (BABYLON = {}));
  44775. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44776. var BABYLON;
  44777. (function (BABYLON) {
  44778. /**
  44779. * The Physically based material of BJS.
  44780. *
  44781. * This offers the main features of a standard PBR material.
  44782. * For more information, please refer to the documentation :
  44783. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44784. */
  44785. var PBRMaterial = /** @class */ (function (_super) {
  44786. __extends(PBRMaterial, _super);
  44787. /**
  44788. * Instantiates a new PBRMaterial instance.
  44789. *
  44790. * @param name The material name
  44791. * @param scene The scene the material will be use in.
  44792. */
  44793. function PBRMaterial(name, scene) {
  44794. var _this = _super.call(this, name, scene) || this;
  44795. /**
  44796. * Intensity of the direct lights e.g. the four lights available in your scene.
  44797. * This impacts both the direct diffuse and specular highlights.
  44798. */
  44799. _this.directIntensity = 1.0;
  44800. /**
  44801. * Intensity of the emissive part of the material.
  44802. * This helps controlling the emissive effect without modifying the emissive color.
  44803. */
  44804. _this.emissiveIntensity = 1.0;
  44805. /**
  44806. * Intensity of the environment e.g. how much the environment will light the object
  44807. * either through harmonics for rough material or through the refelction for shiny ones.
  44808. */
  44809. _this.environmentIntensity = 1.0;
  44810. /**
  44811. * This is a special control allowing the reduction of the specular highlights coming from the
  44812. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44813. */
  44814. _this.specularIntensity = 1.0;
  44815. /**
  44816. * Debug Control allowing disabling the bump map on this material.
  44817. */
  44818. _this.disableBumpMap = false;
  44819. /**
  44820. * AKA Occlusion Texture Intensity in other nomenclature.
  44821. */
  44822. _this.ambientTextureStrength = 1.0;
  44823. /**
  44824. * The color of a material in ambient lighting.
  44825. */
  44826. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44827. /**
  44828. * AKA Diffuse Color in other nomenclature.
  44829. */
  44830. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44831. /**
  44832. * AKA Specular Color in other nomenclature.
  44833. */
  44834. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44835. /**
  44836. * The color reflected from the material.
  44837. */
  44838. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44839. /**
  44840. * The color emitted from the material.
  44841. */
  44842. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44843. /**
  44844. * AKA Glossiness in other nomenclature.
  44845. */
  44846. _this.microSurface = 1.0;
  44847. /**
  44848. * source material index of refraction (IOR)' / 'destination material IOR.
  44849. */
  44850. _this.indexOfRefraction = 0.66;
  44851. /**
  44852. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44853. */
  44854. _this.invertRefractionY = false;
  44855. /**
  44856. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44857. * Materials half opaque for instance using refraction could benefit from this control.
  44858. */
  44859. _this.linkRefractionWithTransparency = false;
  44860. _this.useLightmapAsShadowmap = false;
  44861. /**
  44862. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44863. */
  44864. _this.useAlphaFromAlbedoTexture = false;
  44865. /**
  44866. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44867. */
  44868. _this.forceAlphaTest = false;
  44869. /**
  44870. * Defines the alpha limits in alpha test mode.
  44871. */
  44872. _this.alphaCutOff = 0.4;
  44873. /**
  44874. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44875. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44876. */
  44877. _this.useSpecularOverAlpha = true;
  44878. /**
  44879. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44880. */
  44881. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44882. /**
  44883. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44884. */
  44885. _this.useRoughnessFromMetallicTextureAlpha = true;
  44886. /**
  44887. * Specifies if the metallic texture contains the roughness information in its green channel.
  44888. */
  44889. _this.useRoughnessFromMetallicTextureGreen = false;
  44890. /**
  44891. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44892. */
  44893. _this.useMetallnessFromMetallicTextureBlue = false;
  44894. /**
  44895. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44896. */
  44897. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44898. /**
  44899. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44900. */
  44901. _this.useAmbientInGrayScale = false;
  44902. /**
  44903. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44904. * The material will try to infer what glossiness each pixel should be.
  44905. */
  44906. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44907. /**
  44908. * BJS is using an harcoded light falloff based on a manually sets up range.
  44909. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44910. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44911. */
  44912. _this.usePhysicalLightFalloff = true;
  44913. /**
  44914. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44915. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44916. */
  44917. _this.useRadianceOverAlpha = true;
  44918. /**
  44919. * Allows using an object space normal map (instead of tangent space).
  44920. */
  44921. _this.useObjectSpaceNormalMap = false;
  44922. /**
  44923. * Allows using the bump map in parallax mode.
  44924. */
  44925. _this.useParallax = false;
  44926. /**
  44927. * Allows using the bump map in parallax occlusion mode.
  44928. */
  44929. _this.useParallaxOcclusion = false;
  44930. /**
  44931. * Controls the scale bias of the parallax mode.
  44932. */
  44933. _this.parallaxScaleBias = 0.05;
  44934. /**
  44935. * If sets to true, disables all the lights affecting the material.
  44936. */
  44937. _this.disableLighting = false;
  44938. /**
  44939. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44940. */
  44941. _this.forceIrradianceInFragment = false;
  44942. /**
  44943. * Number of Simultaneous lights allowed on the material.
  44944. */
  44945. _this.maxSimultaneousLights = 4;
  44946. /**
  44947. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44948. */
  44949. _this.invertNormalMapX = false;
  44950. /**
  44951. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44952. */
  44953. _this.invertNormalMapY = false;
  44954. /**
  44955. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44956. */
  44957. _this.twoSidedLighting = false;
  44958. /**
  44959. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44960. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44961. */
  44962. _this.useAlphaFresnel = false;
  44963. /**
  44964. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44965. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44966. */
  44967. _this.useLinearAlphaFresnel = false;
  44968. /**
  44969. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44970. * And/Or occlude the blended part.
  44971. */
  44972. _this.environmentBRDFTexture = null;
  44973. /**
  44974. * Force normal to face away from face.
  44975. */
  44976. _this.forceNormalForward = false;
  44977. /**
  44978. * Enables specular anti aliasing in the PBR shader.
  44979. * It will both interacts on the Geometry for analytical and IBL lighting.
  44980. * It also prefilter the roughness map based on the bump values.
  44981. */
  44982. _this.enableSpecularAntiAliasing = false;
  44983. /**
  44984. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44985. * makes the reflect vector face the model (under horizon).
  44986. */
  44987. _this.useHorizonOcclusion = true;
  44988. /**
  44989. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44990. * too much the area relying on ambient texture to define their ambient occlusion.
  44991. */
  44992. _this.useRadianceOcclusion = true;
  44993. /**
  44994. * If set to true, no lighting calculations will be applied.
  44995. */
  44996. _this.unlit = false;
  44997. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44998. return _this;
  44999. }
  45000. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45001. /**
  45002. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45003. */
  45004. get: function () {
  45005. return this._PBRMATERIAL_OPAQUE;
  45006. },
  45007. enumerable: true,
  45008. configurable: true
  45009. });
  45010. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45011. /**
  45012. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45013. */
  45014. get: function () {
  45015. return this._PBRMATERIAL_ALPHATEST;
  45016. },
  45017. enumerable: true,
  45018. configurable: true
  45019. });
  45020. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45021. /**
  45022. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45023. */
  45024. get: function () {
  45025. return this._PBRMATERIAL_ALPHABLEND;
  45026. },
  45027. enumerable: true,
  45028. configurable: true
  45029. });
  45030. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45031. /**
  45032. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45033. * They are also discarded below the alpha cutoff threshold to improve performances.
  45034. */
  45035. get: function () {
  45036. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45037. },
  45038. enumerable: true,
  45039. configurable: true
  45040. });
  45041. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45042. /**
  45043. * Gets the image processing configuration used either in this material.
  45044. */
  45045. get: function () {
  45046. return this._imageProcessingConfiguration;
  45047. },
  45048. /**
  45049. * Sets the Default image processing configuration used either in the this material.
  45050. *
  45051. * If sets to null, the scene one is in use.
  45052. */
  45053. set: function (value) {
  45054. this._attachImageProcessingConfiguration(value);
  45055. // Ensure the effect will be rebuilt.
  45056. this._markAllSubMeshesAsTexturesDirty();
  45057. },
  45058. enumerable: true,
  45059. configurable: true
  45060. });
  45061. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45062. /**
  45063. * Gets wether the color curves effect is enabled.
  45064. */
  45065. get: function () {
  45066. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45067. },
  45068. /**
  45069. * Sets wether the color curves effect is enabled.
  45070. */
  45071. set: function (value) {
  45072. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45073. },
  45074. enumerable: true,
  45075. configurable: true
  45076. });
  45077. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45078. /**
  45079. * Gets wether the color grading effect is enabled.
  45080. */
  45081. get: function () {
  45082. return this.imageProcessingConfiguration.colorGradingEnabled;
  45083. },
  45084. /**
  45085. * Gets wether the color grading effect is enabled.
  45086. */
  45087. set: function (value) {
  45088. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45089. },
  45090. enumerable: true,
  45091. configurable: true
  45092. });
  45093. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45094. /**
  45095. * Gets wether tonemapping is enabled or not.
  45096. */
  45097. get: function () {
  45098. return this._imageProcessingConfiguration.toneMappingEnabled;
  45099. },
  45100. /**
  45101. * Sets wether tonemapping is enabled or not
  45102. */
  45103. set: function (value) {
  45104. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45105. },
  45106. enumerable: true,
  45107. configurable: true
  45108. });
  45109. ;
  45110. ;
  45111. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45112. /**
  45113. * The camera exposure used on this material.
  45114. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45115. * This corresponds to a photographic exposure.
  45116. */
  45117. get: function () {
  45118. return this._imageProcessingConfiguration.exposure;
  45119. },
  45120. /**
  45121. * The camera exposure used on this material.
  45122. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45123. * This corresponds to a photographic exposure.
  45124. */
  45125. set: function (value) {
  45126. this._imageProcessingConfiguration.exposure = value;
  45127. },
  45128. enumerable: true,
  45129. configurable: true
  45130. });
  45131. ;
  45132. ;
  45133. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45134. /**
  45135. * Gets The camera contrast used on this material.
  45136. */
  45137. get: function () {
  45138. return this._imageProcessingConfiguration.contrast;
  45139. },
  45140. /**
  45141. * Sets The camera contrast used on this material.
  45142. */
  45143. set: function (value) {
  45144. this._imageProcessingConfiguration.contrast = value;
  45145. },
  45146. enumerable: true,
  45147. configurable: true
  45148. });
  45149. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45150. /**
  45151. * Gets the Color Grading 2D Lookup Texture.
  45152. */
  45153. get: function () {
  45154. return this._imageProcessingConfiguration.colorGradingTexture;
  45155. },
  45156. /**
  45157. * Sets the Color Grading 2D Lookup Texture.
  45158. */
  45159. set: function (value) {
  45160. this._imageProcessingConfiguration.colorGradingTexture = value;
  45161. },
  45162. enumerable: true,
  45163. configurable: true
  45164. });
  45165. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45166. /**
  45167. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45168. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45169. * 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;
  45170. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45171. */
  45172. get: function () {
  45173. return this._imageProcessingConfiguration.colorCurves;
  45174. },
  45175. /**
  45176. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45177. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45178. * 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;
  45179. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45180. */
  45181. set: function (value) {
  45182. this._imageProcessingConfiguration.colorCurves = value;
  45183. },
  45184. enumerable: true,
  45185. configurable: true
  45186. });
  45187. /**
  45188. * Returns the name of this material class.
  45189. */
  45190. PBRMaterial.prototype.getClassName = function () {
  45191. return "PBRMaterial";
  45192. };
  45193. /**
  45194. * Returns an array of the actively used textures.
  45195. * @returns - Array of BaseTextures
  45196. */
  45197. PBRMaterial.prototype.getActiveTextures = function () {
  45198. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45199. if (this._albedoTexture) {
  45200. activeTextures.push(this._albedoTexture);
  45201. }
  45202. if (this._ambientTexture) {
  45203. activeTextures.push(this._ambientTexture);
  45204. }
  45205. if (this._opacityTexture) {
  45206. activeTextures.push(this._opacityTexture);
  45207. }
  45208. if (this._reflectionTexture) {
  45209. activeTextures.push(this._reflectionTexture);
  45210. }
  45211. if (this._emissiveTexture) {
  45212. activeTextures.push(this._emissiveTexture);
  45213. }
  45214. if (this._reflectivityTexture) {
  45215. activeTextures.push(this._reflectivityTexture);
  45216. }
  45217. if (this._metallicTexture) {
  45218. activeTextures.push(this._metallicTexture);
  45219. }
  45220. if (this._microSurfaceTexture) {
  45221. activeTextures.push(this._microSurfaceTexture);
  45222. }
  45223. if (this._bumpTexture) {
  45224. activeTextures.push(this._bumpTexture);
  45225. }
  45226. if (this._lightmapTexture) {
  45227. activeTextures.push(this._lightmapTexture);
  45228. }
  45229. if (this._refractionTexture) {
  45230. activeTextures.push(this._refractionTexture);
  45231. }
  45232. return activeTextures;
  45233. };
  45234. /**
  45235. * Checks to see if a texture is used in the material.
  45236. * @param texture - Base texture to use.
  45237. * @returns - Boolean specifying if a texture is used in the material.
  45238. */
  45239. PBRMaterial.prototype.hasTexture = function (texture) {
  45240. if (_super.prototype.hasTexture.call(this, texture)) {
  45241. return true;
  45242. }
  45243. if (this._albedoTexture === texture) {
  45244. return true;
  45245. }
  45246. if (this._ambientTexture === texture) {
  45247. return true;
  45248. }
  45249. if (this._opacityTexture === texture) {
  45250. return true;
  45251. }
  45252. if (this._reflectionTexture === texture) {
  45253. return true;
  45254. }
  45255. if (this._reflectivityTexture === texture) {
  45256. return true;
  45257. }
  45258. if (this._metallicTexture === texture) {
  45259. return true;
  45260. }
  45261. if (this._microSurfaceTexture === texture) {
  45262. return true;
  45263. }
  45264. if (this._bumpTexture === texture) {
  45265. return true;
  45266. }
  45267. if (this._lightmapTexture === texture) {
  45268. return true;
  45269. }
  45270. if (this._refractionTexture === texture) {
  45271. return true;
  45272. }
  45273. return false;
  45274. };
  45275. /**
  45276. * Makes a duplicate of the current material.
  45277. * @param name - name to use for the new material.
  45278. */
  45279. PBRMaterial.prototype.clone = function (name) {
  45280. var _this = this;
  45281. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45282. clone.id = name;
  45283. clone.name = name;
  45284. return clone;
  45285. };
  45286. /**
  45287. * Serializes this PBR Material.
  45288. * @returns - An object with the serialized material.
  45289. */
  45290. PBRMaterial.prototype.serialize = function () {
  45291. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45292. serializationObject.customType = "BABYLON.PBRMaterial";
  45293. return serializationObject;
  45294. };
  45295. // Statics
  45296. /**
  45297. * Parses a PBR Material from a serialized object.
  45298. * @param source - Serialized object.
  45299. * @param scene - BJS scene instance.
  45300. * @param rootUrl - url for the scene object
  45301. * @returns - PBRMaterial
  45302. */
  45303. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45304. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45305. };
  45306. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45307. /**
  45308. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45309. */
  45310. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45311. /**
  45312. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45313. */
  45314. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45315. /**
  45316. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45317. * They are also discarded below the alpha cutoff threshold to improve performances.
  45318. */
  45319. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45320. __decorate([
  45321. BABYLON.serialize(),
  45322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45323. ], PBRMaterial.prototype, "directIntensity", void 0);
  45324. __decorate([
  45325. BABYLON.serialize(),
  45326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45327. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45328. __decorate([
  45329. BABYLON.serialize(),
  45330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45331. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45332. __decorate([
  45333. BABYLON.serialize(),
  45334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45335. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45336. __decorate([
  45337. BABYLON.serialize(),
  45338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45339. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45340. __decorate([
  45341. BABYLON.serializeAsTexture(),
  45342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45343. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45344. __decorate([
  45345. BABYLON.serializeAsTexture(),
  45346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45347. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45348. __decorate([
  45349. BABYLON.serialize(),
  45350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45351. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45352. __decorate([
  45353. BABYLON.serializeAsTexture(),
  45354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45355. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45356. __decorate([
  45357. BABYLON.serializeAsTexture(),
  45358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45359. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45360. __decorate([
  45361. BABYLON.serializeAsTexture(),
  45362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45363. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45364. __decorate([
  45365. BABYLON.serializeAsTexture(),
  45366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45367. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45368. __decorate([
  45369. BABYLON.serializeAsTexture(),
  45370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45371. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45372. __decorate([
  45373. BABYLON.serialize(),
  45374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45375. ], PBRMaterial.prototype, "metallic", void 0);
  45376. __decorate([
  45377. BABYLON.serialize(),
  45378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45379. ], PBRMaterial.prototype, "roughness", void 0);
  45380. __decorate([
  45381. BABYLON.serializeAsTexture(),
  45382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45383. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45384. __decorate([
  45385. BABYLON.serializeAsTexture(),
  45386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45387. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45388. __decorate([
  45389. BABYLON.serializeAsTexture(),
  45390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45391. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45392. __decorate([
  45393. BABYLON.serializeAsTexture(),
  45394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45395. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45396. __decorate([
  45397. BABYLON.serializeAsColor3("ambient"),
  45398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45399. ], PBRMaterial.prototype, "ambientColor", void 0);
  45400. __decorate([
  45401. BABYLON.serializeAsColor3("albedo"),
  45402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45403. ], PBRMaterial.prototype, "albedoColor", void 0);
  45404. __decorate([
  45405. BABYLON.serializeAsColor3("reflectivity"),
  45406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45407. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45408. __decorate([
  45409. BABYLON.serializeAsColor3("reflection"),
  45410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45411. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45412. __decorate([
  45413. BABYLON.serializeAsColor3("emissive"),
  45414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45415. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45416. __decorate([
  45417. BABYLON.serialize(),
  45418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45419. ], PBRMaterial.prototype, "microSurface", void 0);
  45420. __decorate([
  45421. BABYLON.serialize(),
  45422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45423. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45424. __decorate([
  45425. BABYLON.serialize(),
  45426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45427. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45428. __decorate([
  45429. BABYLON.serialize(),
  45430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45431. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45432. __decorate([
  45433. BABYLON.serialize(),
  45434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45435. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45436. __decorate([
  45437. BABYLON.serialize(),
  45438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45439. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45440. __decorate([
  45441. BABYLON.serialize(),
  45442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45443. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45444. __decorate([
  45445. BABYLON.serialize(),
  45446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45447. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45448. __decorate([
  45449. BABYLON.serialize(),
  45450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45451. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45452. __decorate([
  45453. BABYLON.serialize(),
  45454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45455. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45456. __decorate([
  45457. BABYLON.serialize(),
  45458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45459. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45460. __decorate([
  45461. BABYLON.serialize(),
  45462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45463. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45464. __decorate([
  45465. BABYLON.serialize(),
  45466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45467. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45468. __decorate([
  45469. BABYLON.serialize(),
  45470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45471. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45472. __decorate([
  45473. BABYLON.serialize(),
  45474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45475. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45476. __decorate([
  45477. BABYLON.serialize(),
  45478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45479. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45480. __decorate([
  45481. BABYLON.serialize(),
  45482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45483. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45484. __decorate([
  45485. BABYLON.serialize(),
  45486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45487. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45488. __decorate([
  45489. BABYLON.serialize(),
  45490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45491. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45492. __decorate([
  45493. BABYLON.serialize(),
  45494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45495. ], PBRMaterial.prototype, "useParallax", void 0);
  45496. __decorate([
  45497. BABYLON.serialize(),
  45498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45499. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45500. __decorate([
  45501. BABYLON.serialize(),
  45502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45503. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45504. __decorate([
  45505. BABYLON.serialize(),
  45506. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45507. ], PBRMaterial.prototype, "disableLighting", void 0);
  45508. __decorate([
  45509. BABYLON.serialize(),
  45510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45511. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45512. __decorate([
  45513. BABYLON.serialize(),
  45514. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45515. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45516. __decorate([
  45517. BABYLON.serialize(),
  45518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45519. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45520. __decorate([
  45521. BABYLON.serialize(),
  45522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45523. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45524. __decorate([
  45525. BABYLON.serialize(),
  45526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45527. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45528. __decorate([
  45529. BABYLON.serialize(),
  45530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45531. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45532. __decorate([
  45533. BABYLON.serialize(),
  45534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45535. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45536. __decorate([
  45537. BABYLON.serializeAsTexture(),
  45538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45539. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45540. __decorate([
  45541. BABYLON.serialize(),
  45542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45543. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45544. __decorate([
  45545. BABYLON.serialize(),
  45546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45547. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45548. __decorate([
  45549. BABYLON.serialize(),
  45550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45551. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45552. __decorate([
  45553. BABYLON.serialize(),
  45554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45555. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45556. __decorate([
  45557. BABYLON.serialize(),
  45558. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45559. ], PBRMaterial.prototype, "unlit", void 0);
  45560. return PBRMaterial;
  45561. }(BABYLON.PBRBaseMaterial));
  45562. BABYLON.PBRMaterial = PBRMaterial;
  45563. })(BABYLON || (BABYLON = {}));
  45564. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45565. var BABYLON;
  45566. (function (BABYLON) {
  45567. /**
  45568. * The PBR material of BJS following the metal roughness convention.
  45569. *
  45570. * This fits to the PBR convention in the GLTF definition:
  45571. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45572. */
  45573. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45574. __extends(PBRMetallicRoughnessMaterial, _super);
  45575. /**
  45576. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45577. *
  45578. * @param name The material name
  45579. * @param scene The scene the material will be use in.
  45580. */
  45581. function PBRMetallicRoughnessMaterial(name, scene) {
  45582. var _this = _super.call(this, name, scene) || this;
  45583. _this._useRoughnessFromMetallicTextureAlpha = false;
  45584. _this._useRoughnessFromMetallicTextureGreen = true;
  45585. _this._useMetallnessFromMetallicTextureBlue = true;
  45586. _this.metallic = 1.0;
  45587. _this.roughness = 1.0;
  45588. return _this;
  45589. }
  45590. /**
  45591. * Return the currrent class name of the material.
  45592. */
  45593. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45594. return "PBRMetallicRoughnessMaterial";
  45595. };
  45596. /**
  45597. * Return the active textures of the material.
  45598. */
  45599. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45600. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45601. if (this.baseTexture) {
  45602. activeTextures.push(this.baseTexture);
  45603. }
  45604. if (this.metallicRoughnessTexture) {
  45605. activeTextures.push(this.metallicRoughnessTexture);
  45606. }
  45607. return activeTextures;
  45608. };
  45609. /**
  45610. * Checks to see if a texture is used in the material.
  45611. * @param texture - Base texture to use.
  45612. * @returns - Boolean specifying if a texture is used in the material.
  45613. */
  45614. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45615. if (_super.prototype.hasTexture.call(this, texture)) {
  45616. return true;
  45617. }
  45618. if (this.baseTexture === texture) {
  45619. return true;
  45620. }
  45621. if (this.metallicRoughnessTexture === texture) {
  45622. return true;
  45623. }
  45624. return false;
  45625. };
  45626. /**
  45627. * Makes a duplicate of the current material.
  45628. * @param name - name to use for the new material.
  45629. */
  45630. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45631. var _this = this;
  45632. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45633. clone.id = name;
  45634. clone.name = name;
  45635. return clone;
  45636. };
  45637. /**
  45638. * Serialize the material to a parsable JSON object.
  45639. */
  45640. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45641. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45642. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45643. return serializationObject;
  45644. };
  45645. /**
  45646. * Parses a JSON object correponding to the serialize function.
  45647. */
  45648. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45649. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45650. };
  45651. __decorate([
  45652. BABYLON.serializeAsColor3(),
  45653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45654. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45655. __decorate([
  45656. BABYLON.serializeAsTexture(),
  45657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45658. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45659. __decorate([
  45660. BABYLON.serialize(),
  45661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45662. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45663. __decorate([
  45664. BABYLON.serialize(),
  45665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45666. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45667. __decorate([
  45668. BABYLON.serializeAsTexture(),
  45669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45670. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45671. return PBRMetallicRoughnessMaterial;
  45672. }(BABYLON.PBRBaseSimpleMaterial));
  45673. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45674. })(BABYLON || (BABYLON = {}));
  45675. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45676. var BABYLON;
  45677. (function (BABYLON) {
  45678. /**
  45679. * The PBR material of BJS following the specular glossiness convention.
  45680. *
  45681. * This fits to the PBR convention in the GLTF definition:
  45682. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45683. */
  45684. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45685. __extends(PBRSpecularGlossinessMaterial, _super);
  45686. /**
  45687. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45688. *
  45689. * @param name The material name
  45690. * @param scene The scene the material will be use in.
  45691. */
  45692. function PBRSpecularGlossinessMaterial(name, scene) {
  45693. var _this = _super.call(this, name, scene) || this;
  45694. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45695. return _this;
  45696. }
  45697. /**
  45698. * Return the currrent class name of the material.
  45699. */
  45700. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45701. return "PBRSpecularGlossinessMaterial";
  45702. };
  45703. /**
  45704. * Return the active textures of the material.
  45705. */
  45706. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45707. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45708. if (this.diffuseTexture) {
  45709. activeTextures.push(this.diffuseTexture);
  45710. }
  45711. if (this.specularGlossinessTexture) {
  45712. activeTextures.push(this.specularGlossinessTexture);
  45713. }
  45714. return activeTextures;
  45715. };
  45716. /**
  45717. * Checks to see if a texture is used in the material.
  45718. * @param texture - Base texture to use.
  45719. * @returns - Boolean specifying if a texture is used in the material.
  45720. */
  45721. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45722. if (_super.prototype.hasTexture.call(this, texture)) {
  45723. return true;
  45724. }
  45725. if (this.diffuseTexture === texture) {
  45726. return true;
  45727. }
  45728. if (this.specularGlossinessTexture === texture) {
  45729. return true;
  45730. }
  45731. return false;
  45732. };
  45733. /**
  45734. * Makes a duplicate of the current material.
  45735. * @param name - name to use for the new material.
  45736. */
  45737. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45738. var _this = this;
  45739. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45740. clone.id = name;
  45741. clone.name = name;
  45742. return clone;
  45743. };
  45744. /**
  45745. * Serialize the material to a parsable JSON object.
  45746. */
  45747. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45748. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45749. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45750. return serializationObject;
  45751. };
  45752. /**
  45753. * Parses a JSON object correponding to the serialize function.
  45754. */
  45755. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45756. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45757. };
  45758. __decorate([
  45759. BABYLON.serializeAsColor3("diffuse"),
  45760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45761. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45762. __decorate([
  45763. BABYLON.serializeAsTexture(),
  45764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45765. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45766. __decorate([
  45767. BABYLON.serializeAsColor3("specular"),
  45768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45769. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45770. __decorate([
  45771. BABYLON.serialize(),
  45772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45773. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45774. __decorate([
  45775. BABYLON.serializeAsTexture(),
  45776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45777. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45778. return PBRSpecularGlossinessMaterial;
  45779. }(BABYLON.PBRBaseSimpleMaterial));
  45780. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45781. })(BABYLON || (BABYLON = {}));
  45782. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45783. var BABYLON;
  45784. (function (BABYLON) {
  45785. BABYLON.CameraInputTypes = {};
  45786. var CameraInputsManager = /** @class */ (function () {
  45787. function CameraInputsManager(camera) {
  45788. this.attached = {};
  45789. this.camera = camera;
  45790. this.checkInputs = function () { };
  45791. }
  45792. /**
  45793. * Add an input method to a camera
  45794. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45795. * @param input camera input method
  45796. */
  45797. CameraInputsManager.prototype.add = function (input) {
  45798. var type = input.getSimpleName();
  45799. if (this.attached[type]) {
  45800. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45801. return;
  45802. }
  45803. this.attached[type] = input;
  45804. input.camera = this.camera;
  45805. //for checkInputs, we are dynamically creating a function
  45806. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45807. if (input.checkInputs) {
  45808. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45809. }
  45810. if (this.attachedElement) {
  45811. input.attachControl(this.attachedElement);
  45812. }
  45813. };
  45814. /**
  45815. * Remove a specific input method from a camera
  45816. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45817. * @param inputToRemove camera input method
  45818. */
  45819. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45820. for (var cam in this.attached) {
  45821. var input = this.attached[cam];
  45822. if (input === inputToRemove) {
  45823. input.detachControl(this.attachedElement);
  45824. input.camera = null;
  45825. delete this.attached[cam];
  45826. this.rebuildInputCheck();
  45827. }
  45828. }
  45829. };
  45830. CameraInputsManager.prototype.removeByType = function (inputType) {
  45831. for (var cam in this.attached) {
  45832. var input = this.attached[cam];
  45833. if (input.getClassName() === inputType) {
  45834. input.detachControl(this.attachedElement);
  45835. input.camera = null;
  45836. delete this.attached[cam];
  45837. this.rebuildInputCheck();
  45838. }
  45839. }
  45840. };
  45841. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45842. var current = this.checkInputs;
  45843. return function () {
  45844. current();
  45845. fn();
  45846. };
  45847. };
  45848. CameraInputsManager.prototype.attachInput = function (input) {
  45849. if (this.attachedElement) {
  45850. input.attachControl(this.attachedElement, this.noPreventDefault);
  45851. }
  45852. };
  45853. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45854. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45855. if (this.attachedElement) {
  45856. return;
  45857. }
  45858. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45859. this.attachedElement = element;
  45860. this.noPreventDefault = noPreventDefault;
  45861. for (var cam in this.attached) {
  45862. this.attached[cam].attachControl(element, noPreventDefault);
  45863. }
  45864. };
  45865. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45866. if (disconnect === void 0) { disconnect = false; }
  45867. if (this.attachedElement !== element) {
  45868. return;
  45869. }
  45870. for (var cam in this.attached) {
  45871. this.attached[cam].detachControl(element);
  45872. if (disconnect) {
  45873. this.attached[cam].camera = null;
  45874. }
  45875. }
  45876. this.attachedElement = null;
  45877. };
  45878. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45879. this.checkInputs = function () { };
  45880. for (var cam in this.attached) {
  45881. var input = this.attached[cam];
  45882. if (input.checkInputs) {
  45883. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45884. }
  45885. }
  45886. };
  45887. /**
  45888. * Remove all attached input methods from a camera
  45889. */
  45890. CameraInputsManager.prototype.clear = function () {
  45891. if (this.attachedElement) {
  45892. this.detachElement(this.attachedElement, true);
  45893. }
  45894. this.attached = {};
  45895. this.attachedElement = null;
  45896. this.checkInputs = function () { };
  45897. };
  45898. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45899. var inputs = {};
  45900. for (var cam in this.attached) {
  45901. var input = this.attached[cam];
  45902. var res = BABYLON.SerializationHelper.Serialize(input);
  45903. inputs[input.getClassName()] = res;
  45904. }
  45905. serializedCamera.inputsmgr = inputs;
  45906. };
  45907. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45908. var parsedInputs = parsedCamera.inputsmgr;
  45909. if (parsedInputs) {
  45910. this.clear();
  45911. for (var n in parsedInputs) {
  45912. var construct = BABYLON.CameraInputTypes[n];
  45913. if (construct) {
  45914. var parsedinput = parsedInputs[n];
  45915. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45916. this.add(input);
  45917. }
  45918. }
  45919. }
  45920. else {
  45921. //2016-03-08 this part is for managing backward compatibility
  45922. for (var n in this.attached) {
  45923. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45924. if (construct) {
  45925. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45926. this.remove(this.attached[n]);
  45927. this.add(input);
  45928. }
  45929. }
  45930. }
  45931. };
  45932. return CameraInputsManager;
  45933. }());
  45934. BABYLON.CameraInputsManager = CameraInputsManager;
  45935. })(BABYLON || (BABYLON = {}));
  45936. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45937. var BABYLON;
  45938. (function (BABYLON) {
  45939. var TargetCamera = /** @class */ (function (_super) {
  45940. __extends(TargetCamera, _super);
  45941. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45942. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45943. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45944. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45945. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45946. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45947. _this.speed = 2.0;
  45948. _this.noRotationConstraint = false;
  45949. _this.lockedTarget = null;
  45950. _this._currentTarget = BABYLON.Vector3.Zero();
  45951. _this._viewMatrix = BABYLON.Matrix.Zero();
  45952. _this._camMatrix = BABYLON.Matrix.Zero();
  45953. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45954. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45955. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45956. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45957. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45958. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45959. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45960. return _this;
  45961. }
  45962. TargetCamera.prototype.getFrontPosition = function (distance) {
  45963. this.getWorldMatrix();
  45964. var direction = this.getTarget().subtract(this.position);
  45965. direction.normalize();
  45966. direction.scaleInPlace(distance);
  45967. return this.globalPosition.add(direction);
  45968. };
  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. */
  45989. TargetCamera.prototype._restoreStateValues = function () {
  45990. if (!_super.prototype._restoreStateValues.call(this)) {
  45991. return false;
  45992. }
  45993. this.position = this._storedPosition.clone();
  45994. this.rotation = this._storedRotation.clone();
  45995. if (this.rotationQuaternion) {
  45996. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45997. }
  45998. this.cameraDirection.copyFromFloats(0, 0, 0);
  45999. this.cameraRotation.copyFromFloats(0, 0);
  46000. return true;
  46001. };
  46002. // Cache
  46003. TargetCamera.prototype._initCache = function () {
  46004. _super.prototype._initCache.call(this);
  46005. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46006. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46007. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46008. };
  46009. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46010. if (!ignoreParentClass) {
  46011. _super.prototype._updateCache.call(this);
  46012. }
  46013. var lockedTargetPosition = this._getLockedTargetPosition();
  46014. if (!lockedTargetPosition) {
  46015. this._cache.lockedTarget = null;
  46016. }
  46017. else {
  46018. if (!this._cache.lockedTarget) {
  46019. this._cache.lockedTarget = lockedTargetPosition.clone();
  46020. }
  46021. else {
  46022. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46023. }
  46024. }
  46025. this._cache.rotation.copyFrom(this.rotation);
  46026. if (this.rotationQuaternion)
  46027. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46028. };
  46029. // Synchronized
  46030. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46031. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46032. return false;
  46033. }
  46034. var lockedTargetPosition = this._getLockedTargetPosition();
  46035. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46036. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46037. };
  46038. // Methods
  46039. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46040. var engine = this.getEngine();
  46041. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46042. };
  46043. // Target
  46044. TargetCamera.prototype.setTarget = function (target) {
  46045. this.upVector.normalize();
  46046. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46047. this._camMatrix.invert();
  46048. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46049. var vDir = target.subtract(this.position);
  46050. if (vDir.x >= 0.0) {
  46051. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46052. }
  46053. else {
  46054. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46055. }
  46056. this.rotation.z = 0;
  46057. if (isNaN(this.rotation.x)) {
  46058. this.rotation.x = 0;
  46059. }
  46060. if (isNaN(this.rotation.y)) {
  46061. this.rotation.y = 0;
  46062. }
  46063. if (isNaN(this.rotation.z)) {
  46064. this.rotation.z = 0;
  46065. }
  46066. if (this.rotationQuaternion) {
  46067. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46068. }
  46069. };
  46070. /**
  46071. * Return the current target position of the camera. This value is expressed in local space.
  46072. */
  46073. TargetCamera.prototype.getTarget = function () {
  46074. return this._currentTarget;
  46075. };
  46076. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46077. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46078. };
  46079. TargetCamera.prototype._updatePosition = function () {
  46080. if (this.parent) {
  46081. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46082. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46083. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46084. return;
  46085. }
  46086. this.position.addInPlace(this.cameraDirection);
  46087. };
  46088. TargetCamera.prototype._checkInputs = function () {
  46089. var needToMove = this._decideIfNeedsToMove();
  46090. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46091. // Move
  46092. if (needToMove) {
  46093. this._updatePosition();
  46094. }
  46095. // Rotate
  46096. if (needToRotate) {
  46097. this.rotation.x += this.cameraRotation.x;
  46098. this.rotation.y += this.cameraRotation.y;
  46099. //rotate, if quaternion is set and rotation was used
  46100. if (this.rotationQuaternion) {
  46101. var len = this.rotation.lengthSquared();
  46102. if (len) {
  46103. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46104. }
  46105. }
  46106. if (!this.noRotationConstraint) {
  46107. var limit = (Math.PI / 2) * 0.95;
  46108. if (this.rotation.x > limit)
  46109. this.rotation.x = limit;
  46110. if (this.rotation.x < -limit)
  46111. this.rotation.x = -limit;
  46112. }
  46113. }
  46114. // Inertia
  46115. if (needToMove) {
  46116. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46117. this.cameraDirection.x = 0;
  46118. }
  46119. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46120. this.cameraDirection.y = 0;
  46121. }
  46122. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46123. this.cameraDirection.z = 0;
  46124. }
  46125. this.cameraDirection.scaleInPlace(this.inertia);
  46126. }
  46127. if (needToRotate) {
  46128. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46129. this.cameraRotation.x = 0;
  46130. }
  46131. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46132. this.cameraRotation.y = 0;
  46133. }
  46134. this.cameraRotation.scaleInPlace(this.inertia);
  46135. }
  46136. _super.prototype._checkInputs.call(this);
  46137. };
  46138. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46139. if (this.rotationQuaternion) {
  46140. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46141. }
  46142. else {
  46143. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46144. }
  46145. //update the up vector!
  46146. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46147. };
  46148. TargetCamera.prototype._getViewMatrix = function () {
  46149. if (this.lockedTarget) {
  46150. this.setTarget(this._getLockedTargetPosition());
  46151. }
  46152. // Compute
  46153. this._updateCameraRotationMatrix();
  46154. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46155. // Computing target and final matrix
  46156. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46157. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46158. return this._viewMatrix;
  46159. };
  46160. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46161. if (this.parent) {
  46162. var parentWorldMatrix = this.parent.getWorldMatrix();
  46163. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46164. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46165. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46166. this._markSyncedWithParent();
  46167. }
  46168. else {
  46169. this._globalPosition.copyFrom(this.position);
  46170. this._globalCurrentTarget.copyFrom(target);
  46171. this._globalCurrentUpVector.copyFrom(up);
  46172. }
  46173. if (this.getScene().useRightHandedSystem) {
  46174. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46175. }
  46176. else {
  46177. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46178. }
  46179. };
  46180. /**
  46181. * @override
  46182. * Override Camera.createRigCamera
  46183. */
  46184. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46185. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46186. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46187. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46188. if (!this.rotationQuaternion) {
  46189. this.rotationQuaternion = new BABYLON.Quaternion();
  46190. }
  46191. rigCamera._cameraRigParams = {};
  46192. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46193. }
  46194. return rigCamera;
  46195. }
  46196. return null;
  46197. };
  46198. /**
  46199. * @override
  46200. * Override Camera._updateRigCameras
  46201. */
  46202. TargetCamera.prototype._updateRigCameras = function () {
  46203. var camLeft = this._rigCameras[0];
  46204. var camRight = this._rigCameras[1];
  46205. switch (this.cameraRigMode) {
  46206. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46207. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46208. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46209. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46210. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46211. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46212. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46213. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46214. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46215. camLeft.setTarget(this.getTarget());
  46216. camRight.setTarget(this.getTarget());
  46217. break;
  46218. case BABYLON.Camera.RIG_MODE_VR:
  46219. if (camLeft.rotationQuaternion) {
  46220. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46221. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46222. }
  46223. else {
  46224. camLeft.rotation.copyFrom(this.rotation);
  46225. camRight.rotation.copyFrom(this.rotation);
  46226. }
  46227. camLeft.position.copyFrom(this.position);
  46228. camRight.position.copyFrom(this.position);
  46229. break;
  46230. }
  46231. _super.prototype._updateRigCameras.call(this);
  46232. };
  46233. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46234. if (!this._rigCamTransformMatrix) {
  46235. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46236. }
  46237. var target = this.getTarget();
  46238. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46239. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46240. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46241. };
  46242. TargetCamera.prototype.getClassName = function () {
  46243. return "TargetCamera";
  46244. };
  46245. __decorate([
  46246. BABYLON.serializeAsVector3()
  46247. ], TargetCamera.prototype, "rotation", void 0);
  46248. __decorate([
  46249. BABYLON.serialize()
  46250. ], TargetCamera.prototype, "speed", void 0);
  46251. __decorate([
  46252. BABYLON.serializeAsMeshReference("lockedTargetId")
  46253. ], TargetCamera.prototype, "lockedTarget", void 0);
  46254. return TargetCamera;
  46255. }(BABYLON.Camera));
  46256. BABYLON.TargetCamera = TargetCamera;
  46257. })(BABYLON || (BABYLON = {}));
  46258. //# sourceMappingURL=babylon.targetCamera.js.map
  46259. var BABYLON;
  46260. (function (BABYLON) {
  46261. var FreeCameraMouseInput = /** @class */ (function () {
  46262. function FreeCameraMouseInput(touchEnabled) {
  46263. if (touchEnabled === void 0) { touchEnabled = true; }
  46264. this.touchEnabled = touchEnabled;
  46265. this.buttons = [0, 1, 2];
  46266. this.angularSensibility = 2000.0;
  46267. this.previousPosition = null;
  46268. }
  46269. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46270. var _this = this;
  46271. var engine = this.camera.getEngine();
  46272. if (!this._pointerInput) {
  46273. this._pointerInput = function (p, s) {
  46274. var evt = p.event;
  46275. if (engine.isInVRExclusivePointerMode) {
  46276. return;
  46277. }
  46278. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46279. return;
  46280. }
  46281. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46282. return;
  46283. }
  46284. var srcElement = (evt.srcElement || evt.target);
  46285. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46286. try {
  46287. srcElement.setPointerCapture(evt.pointerId);
  46288. }
  46289. catch (e) {
  46290. //Nothing to do with the error. Execution will continue.
  46291. }
  46292. _this.previousPosition = {
  46293. x: evt.clientX,
  46294. y: evt.clientY
  46295. };
  46296. if (!noPreventDefault) {
  46297. evt.preventDefault();
  46298. element.focus();
  46299. }
  46300. }
  46301. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46302. try {
  46303. srcElement.releasePointerCapture(evt.pointerId);
  46304. }
  46305. catch (e) {
  46306. //Nothing to do with the error.
  46307. }
  46308. _this.previousPosition = null;
  46309. if (!noPreventDefault) {
  46310. evt.preventDefault();
  46311. }
  46312. }
  46313. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46314. if (!_this.previousPosition || engine.isPointerLock) {
  46315. return;
  46316. }
  46317. var offsetX = evt.clientX - _this.previousPosition.x;
  46318. if (_this.camera.getScene().useRightHandedSystem)
  46319. offsetX *= -1;
  46320. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46321. offsetX *= -1;
  46322. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46323. var offsetY = evt.clientY - _this.previousPosition.y;
  46324. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46325. _this.previousPosition = {
  46326. x: evt.clientX,
  46327. y: evt.clientY
  46328. };
  46329. if (!noPreventDefault) {
  46330. evt.preventDefault();
  46331. }
  46332. }
  46333. };
  46334. }
  46335. this._onMouseMove = function (evt) {
  46336. if (!engine.isPointerLock) {
  46337. return;
  46338. }
  46339. if (engine.isInVRExclusivePointerMode) {
  46340. return;
  46341. }
  46342. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46343. if (_this.camera.getScene().useRightHandedSystem)
  46344. offsetX *= -1;
  46345. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46346. offsetX *= -1;
  46347. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46348. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46349. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46350. _this.previousPosition = null;
  46351. if (!noPreventDefault) {
  46352. evt.preventDefault();
  46353. }
  46354. };
  46355. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46356. element.addEventListener("mousemove", this._onMouseMove, false);
  46357. };
  46358. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46359. if (this._observer && element) {
  46360. this.camera.getScene().onPointerObservable.remove(this._observer);
  46361. if (this._onMouseMove) {
  46362. element.removeEventListener("mousemove", this._onMouseMove);
  46363. }
  46364. this._observer = null;
  46365. this._onMouseMove = null;
  46366. this.previousPosition = null;
  46367. }
  46368. };
  46369. FreeCameraMouseInput.prototype.getClassName = function () {
  46370. return "FreeCameraMouseInput";
  46371. };
  46372. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46373. return "mouse";
  46374. };
  46375. __decorate([
  46376. BABYLON.serialize()
  46377. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46378. __decorate([
  46379. BABYLON.serialize()
  46380. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46381. return FreeCameraMouseInput;
  46382. }());
  46383. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46384. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46385. })(BABYLON || (BABYLON = {}));
  46386. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46387. var BABYLON;
  46388. (function (BABYLON) {
  46389. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46390. function FreeCameraKeyboardMoveInput() {
  46391. this._keys = new Array();
  46392. this.keysUp = [38];
  46393. this.keysDown = [40];
  46394. this.keysLeft = [37];
  46395. this.keysRight = [39];
  46396. }
  46397. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46398. var _this = this;
  46399. if (this._onCanvasBlurObserver) {
  46400. return;
  46401. }
  46402. this._scene = this.camera.getScene();
  46403. this._engine = this._scene.getEngine();
  46404. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46405. _this._keys = [];
  46406. });
  46407. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46408. var evt = info.event;
  46409. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46410. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46411. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46412. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46413. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46414. var index = _this._keys.indexOf(evt.keyCode);
  46415. if (index === -1) {
  46416. _this._keys.push(evt.keyCode);
  46417. }
  46418. if (!noPreventDefault) {
  46419. evt.preventDefault();
  46420. }
  46421. }
  46422. }
  46423. else {
  46424. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46425. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46426. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46427. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46428. var index = _this._keys.indexOf(evt.keyCode);
  46429. if (index >= 0) {
  46430. _this._keys.splice(index, 1);
  46431. }
  46432. if (!noPreventDefault) {
  46433. evt.preventDefault();
  46434. }
  46435. }
  46436. }
  46437. });
  46438. };
  46439. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46440. if (this._scene) {
  46441. if (this._onKeyboardObserver) {
  46442. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46443. }
  46444. if (this._onCanvasBlurObserver) {
  46445. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46446. }
  46447. this._onKeyboardObserver = null;
  46448. this._onCanvasBlurObserver = null;
  46449. }
  46450. this._keys = [];
  46451. };
  46452. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46453. if (this._onKeyboardObserver) {
  46454. var camera = this.camera;
  46455. // Keyboard
  46456. for (var index = 0; index < this._keys.length; index++) {
  46457. var keyCode = this._keys[index];
  46458. var speed = camera._computeLocalCameraSpeed();
  46459. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46460. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46461. }
  46462. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46463. camera._localDirection.copyFromFloats(0, 0, speed);
  46464. }
  46465. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46466. camera._localDirection.copyFromFloats(speed, 0, 0);
  46467. }
  46468. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46469. camera._localDirection.copyFromFloats(0, 0, -speed);
  46470. }
  46471. if (camera.getScene().useRightHandedSystem) {
  46472. camera._localDirection.z *= -1;
  46473. }
  46474. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46475. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46476. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46477. }
  46478. }
  46479. };
  46480. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46481. return "FreeCameraKeyboardMoveInput";
  46482. };
  46483. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46484. this._keys = [];
  46485. };
  46486. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46487. return "keyboard";
  46488. };
  46489. __decorate([
  46490. BABYLON.serialize()
  46491. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46492. __decorate([
  46493. BABYLON.serialize()
  46494. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46495. __decorate([
  46496. BABYLON.serialize()
  46497. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46498. __decorate([
  46499. BABYLON.serialize()
  46500. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46501. return FreeCameraKeyboardMoveInput;
  46502. }());
  46503. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46504. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46505. })(BABYLON || (BABYLON = {}));
  46506. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46507. var BABYLON;
  46508. (function (BABYLON) {
  46509. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46510. __extends(FreeCameraInputsManager, _super);
  46511. function FreeCameraInputsManager(camera) {
  46512. return _super.call(this, camera) || this;
  46513. }
  46514. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46515. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46516. return this;
  46517. };
  46518. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46519. if (touchEnabled === void 0) { touchEnabled = true; }
  46520. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46521. return this;
  46522. };
  46523. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46524. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46525. return this;
  46526. };
  46527. FreeCameraInputsManager.prototype.addTouch = function () {
  46528. this.add(new BABYLON.FreeCameraTouchInput());
  46529. return this;
  46530. };
  46531. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46532. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46533. return this;
  46534. };
  46535. return FreeCameraInputsManager;
  46536. }(BABYLON.CameraInputsManager));
  46537. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46538. })(BABYLON || (BABYLON = {}));
  46539. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46540. var BABYLON;
  46541. (function (BABYLON) {
  46542. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46543. // Forcing to use the Universal camera
  46544. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46545. });
  46546. var FreeCamera = /** @class */ (function (_super) {
  46547. __extends(FreeCamera, _super);
  46548. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46549. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46550. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46551. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46552. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46553. _this.checkCollisions = false;
  46554. _this.applyGravity = false;
  46555. _this._needMoveForGravity = false;
  46556. _this._oldPosition = BABYLON.Vector3.Zero();
  46557. _this._diffPosition = BABYLON.Vector3.Zero();
  46558. _this._newPosition = BABYLON.Vector3.Zero();
  46559. // Collisions
  46560. _this._collisionMask = -1;
  46561. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46562. if (collidedMesh === void 0) { collidedMesh = null; }
  46563. //TODO move this to the collision coordinator!
  46564. if (_this.getScene().workerCollisions)
  46565. newPosition.multiplyInPlace(_this._collider._radius);
  46566. var updatePosition = function (newPos) {
  46567. _this._newPosition.copyFrom(newPos);
  46568. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46569. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46570. _this.position.addInPlace(_this._diffPosition);
  46571. if (_this.onCollide && collidedMesh) {
  46572. _this.onCollide(collidedMesh);
  46573. }
  46574. }
  46575. };
  46576. updatePosition(newPosition);
  46577. };
  46578. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46579. _this.inputs.addKeyboard().addMouse();
  46580. return _this;
  46581. }
  46582. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46583. //-- begin properties for backward compatibility for inputs
  46584. /**
  46585. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46586. * Higher values reduce sensitivity.
  46587. */
  46588. get: function () {
  46589. var mouse = this.inputs.attached["mouse"];
  46590. if (mouse)
  46591. return mouse.angularSensibility;
  46592. return 0;
  46593. },
  46594. /**
  46595. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46596. * Higher values reduce sensitivity.
  46597. */
  46598. set: function (value) {
  46599. var mouse = this.inputs.attached["mouse"];
  46600. if (mouse)
  46601. mouse.angularSensibility = value;
  46602. },
  46603. enumerable: true,
  46604. configurable: true
  46605. });
  46606. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46607. get: function () {
  46608. var keyboard = this.inputs.attached["keyboard"];
  46609. if (keyboard)
  46610. return keyboard.keysUp;
  46611. return [];
  46612. },
  46613. set: function (value) {
  46614. var keyboard = this.inputs.attached["keyboard"];
  46615. if (keyboard)
  46616. keyboard.keysUp = value;
  46617. },
  46618. enumerable: true,
  46619. configurable: true
  46620. });
  46621. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46622. get: function () {
  46623. var keyboard = this.inputs.attached["keyboard"];
  46624. if (keyboard)
  46625. return keyboard.keysDown;
  46626. return [];
  46627. },
  46628. set: function (value) {
  46629. var keyboard = this.inputs.attached["keyboard"];
  46630. if (keyboard)
  46631. keyboard.keysDown = value;
  46632. },
  46633. enumerable: true,
  46634. configurable: true
  46635. });
  46636. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46637. get: function () {
  46638. var keyboard = this.inputs.attached["keyboard"];
  46639. if (keyboard)
  46640. return keyboard.keysLeft;
  46641. return [];
  46642. },
  46643. set: function (value) {
  46644. var keyboard = this.inputs.attached["keyboard"];
  46645. if (keyboard)
  46646. keyboard.keysLeft = value;
  46647. },
  46648. enumerable: true,
  46649. configurable: true
  46650. });
  46651. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46652. get: function () {
  46653. var keyboard = this.inputs.attached["keyboard"];
  46654. if (keyboard)
  46655. return keyboard.keysRight;
  46656. return [];
  46657. },
  46658. set: function (value) {
  46659. var keyboard = this.inputs.attached["keyboard"];
  46660. if (keyboard)
  46661. keyboard.keysRight = value;
  46662. },
  46663. enumerable: true,
  46664. configurable: true
  46665. });
  46666. // Controls
  46667. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46668. this.inputs.attachElement(element, noPreventDefault);
  46669. };
  46670. FreeCamera.prototype.detachControl = function (element) {
  46671. this.inputs.detachElement(element);
  46672. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46673. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46674. };
  46675. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46676. get: function () {
  46677. return this._collisionMask;
  46678. },
  46679. set: function (mask) {
  46680. this._collisionMask = !isNaN(mask) ? mask : -1;
  46681. },
  46682. enumerable: true,
  46683. configurable: true
  46684. });
  46685. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46686. var globalPosition;
  46687. if (this.parent) {
  46688. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46689. }
  46690. else {
  46691. globalPosition = this.position;
  46692. }
  46693. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46694. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46695. if (!this._collider) {
  46696. this._collider = new BABYLON.Collider();
  46697. }
  46698. this._collider._radius = this.ellipsoid;
  46699. this._collider.collisionMask = this._collisionMask;
  46700. //no need for clone, as long as gravity is not on.
  46701. var actualDisplacement = displacement;
  46702. //add gravity to the direction to prevent the dual-collision checking
  46703. if (this.applyGravity) {
  46704. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46705. actualDisplacement = displacement.add(this.getScene().gravity);
  46706. }
  46707. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46708. };
  46709. FreeCamera.prototype._checkInputs = function () {
  46710. if (!this._localDirection) {
  46711. this._localDirection = BABYLON.Vector3.Zero();
  46712. this._transformedDirection = BABYLON.Vector3.Zero();
  46713. }
  46714. this.inputs.checkInputs();
  46715. _super.prototype._checkInputs.call(this);
  46716. };
  46717. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46718. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46719. };
  46720. FreeCamera.prototype._updatePosition = function () {
  46721. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46722. this._collideWithWorld(this.cameraDirection);
  46723. }
  46724. else {
  46725. _super.prototype._updatePosition.call(this);
  46726. }
  46727. };
  46728. FreeCamera.prototype.dispose = function () {
  46729. this.inputs.clear();
  46730. _super.prototype.dispose.call(this);
  46731. };
  46732. FreeCamera.prototype.getClassName = function () {
  46733. return "FreeCamera";
  46734. };
  46735. __decorate([
  46736. BABYLON.serializeAsVector3()
  46737. ], FreeCamera.prototype, "ellipsoid", void 0);
  46738. __decorate([
  46739. BABYLON.serializeAsVector3()
  46740. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46741. __decorate([
  46742. BABYLON.serialize()
  46743. ], FreeCamera.prototype, "checkCollisions", void 0);
  46744. __decorate([
  46745. BABYLON.serialize()
  46746. ], FreeCamera.prototype, "applyGravity", void 0);
  46747. return FreeCamera;
  46748. }(BABYLON.TargetCamera));
  46749. BABYLON.FreeCamera = FreeCamera;
  46750. })(BABYLON || (BABYLON = {}));
  46751. //# sourceMappingURL=babylon.freeCamera.js.map
  46752. var BABYLON;
  46753. (function (BABYLON) {
  46754. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46755. function ArcRotateCameraKeyboardMoveInput() {
  46756. this._keys = new Array();
  46757. this.keysUp = [38];
  46758. this.keysDown = [40];
  46759. this.keysLeft = [37];
  46760. this.keysRight = [39];
  46761. this.keysReset = [220];
  46762. this.panningSensibility = 50.0;
  46763. this.zoomingSensibility = 25.0;
  46764. this.useAltToZoom = true;
  46765. }
  46766. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46767. var _this = this;
  46768. if (this._onCanvasBlurObserver) {
  46769. return;
  46770. }
  46771. this._scene = this.camera.getScene();
  46772. this._engine = this._scene.getEngine();
  46773. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46774. _this._keys = [];
  46775. });
  46776. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46777. var evt = info.event;
  46778. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46779. _this._ctrlPressed = evt.ctrlKey;
  46780. _this._altPressed = evt.altKey;
  46781. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46782. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46783. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46784. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46785. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46786. var index = _this._keys.indexOf(evt.keyCode);
  46787. if (index === -1) {
  46788. _this._keys.push(evt.keyCode);
  46789. }
  46790. if (evt.preventDefault) {
  46791. if (!noPreventDefault) {
  46792. evt.preventDefault();
  46793. }
  46794. }
  46795. }
  46796. }
  46797. else {
  46798. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46799. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46800. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46801. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46802. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46803. var index = _this._keys.indexOf(evt.keyCode);
  46804. if (index >= 0) {
  46805. _this._keys.splice(index, 1);
  46806. }
  46807. if (evt.preventDefault) {
  46808. if (!noPreventDefault) {
  46809. evt.preventDefault();
  46810. }
  46811. }
  46812. }
  46813. }
  46814. });
  46815. };
  46816. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46817. if (this._scene) {
  46818. if (this._onKeyboardObserver) {
  46819. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46820. }
  46821. if (this._onCanvasBlurObserver) {
  46822. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46823. }
  46824. this._onKeyboardObserver = null;
  46825. this._onCanvasBlurObserver = null;
  46826. }
  46827. this._keys = [];
  46828. };
  46829. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46830. if (this._onKeyboardObserver) {
  46831. var camera = this.camera;
  46832. for (var index = 0; index < this._keys.length; index++) {
  46833. var keyCode = this._keys[index];
  46834. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46835. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46836. camera.inertialPanningX -= 1 / this.panningSensibility;
  46837. }
  46838. else {
  46839. camera.inertialAlphaOffset -= 0.01;
  46840. }
  46841. }
  46842. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46843. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46844. camera.inertialPanningY += 1 / this.panningSensibility;
  46845. }
  46846. else if (this._altPressed && this.useAltToZoom) {
  46847. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46848. }
  46849. else {
  46850. camera.inertialBetaOffset -= 0.01;
  46851. }
  46852. }
  46853. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46854. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46855. camera.inertialPanningX += 1 / this.panningSensibility;
  46856. }
  46857. else {
  46858. camera.inertialAlphaOffset += 0.01;
  46859. }
  46860. }
  46861. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46862. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46863. camera.inertialPanningY -= 1 / this.panningSensibility;
  46864. }
  46865. else if (this._altPressed && this.useAltToZoom) {
  46866. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46867. }
  46868. else {
  46869. camera.inertialBetaOffset += 0.01;
  46870. }
  46871. }
  46872. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46873. camera.restoreState();
  46874. }
  46875. }
  46876. }
  46877. };
  46878. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46879. return "ArcRotateCameraKeyboardMoveInput";
  46880. };
  46881. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46882. return "keyboard";
  46883. };
  46884. __decorate([
  46885. BABYLON.serialize()
  46886. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46887. __decorate([
  46888. BABYLON.serialize()
  46889. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46890. __decorate([
  46891. BABYLON.serialize()
  46892. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46893. __decorate([
  46894. BABYLON.serialize()
  46895. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46896. __decorate([
  46897. BABYLON.serialize()
  46898. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46899. __decorate([
  46900. BABYLON.serialize()
  46901. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46902. __decorate([
  46903. BABYLON.serialize()
  46904. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46905. __decorate([
  46906. BABYLON.serialize()
  46907. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46908. return ArcRotateCameraKeyboardMoveInput;
  46909. }());
  46910. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46911. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46912. })(BABYLON || (BABYLON = {}));
  46913. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46914. var BABYLON;
  46915. (function (BABYLON) {
  46916. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46917. function ArcRotateCameraMouseWheelInput() {
  46918. this.wheelPrecision = 3.0;
  46919. /**
  46920. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46921. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46922. */
  46923. this.wheelDeltaPercentage = 0;
  46924. }
  46925. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46926. var _this = this;
  46927. this._wheel = function (p, s) {
  46928. //sanity check - this should be a PointerWheel event.
  46929. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46930. return;
  46931. var event = p.event;
  46932. var delta = 0;
  46933. if (event.wheelDelta) {
  46934. if (_this.wheelDeltaPercentage) {
  46935. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46936. if (event.wheelDelta > 0) {
  46937. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46938. }
  46939. else {
  46940. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46941. }
  46942. }
  46943. else {
  46944. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46945. }
  46946. }
  46947. else if (event.detail) {
  46948. delta = -event.detail / _this.wheelPrecision;
  46949. }
  46950. if (delta)
  46951. _this.camera.inertialRadiusOffset += delta;
  46952. if (event.preventDefault) {
  46953. if (!noPreventDefault) {
  46954. event.preventDefault();
  46955. }
  46956. }
  46957. };
  46958. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46959. };
  46960. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46961. if (this._observer && element) {
  46962. this.camera.getScene().onPointerObservable.remove(this._observer);
  46963. this._observer = null;
  46964. this._wheel = null;
  46965. }
  46966. };
  46967. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46968. return "ArcRotateCameraMouseWheelInput";
  46969. };
  46970. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46971. return "mousewheel";
  46972. };
  46973. __decorate([
  46974. BABYLON.serialize()
  46975. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46976. __decorate([
  46977. BABYLON.serialize()
  46978. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46979. return ArcRotateCameraMouseWheelInput;
  46980. }());
  46981. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46982. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46983. })(BABYLON || (BABYLON = {}));
  46984. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46985. var BABYLON;
  46986. (function (BABYLON) {
  46987. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46988. function ArcRotateCameraPointersInput() {
  46989. this.buttons = [0, 1, 2];
  46990. this.angularSensibilityX = 1000.0;
  46991. this.angularSensibilityY = 1000.0;
  46992. this.pinchPrecision = 12.0;
  46993. /**
  46994. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46995. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46996. */
  46997. this.pinchDeltaPercentage = 0;
  46998. this.panningSensibility = 1000.0;
  46999. this.multiTouchPanning = true;
  47000. this.multiTouchPanAndZoom = true;
  47001. this._isPanClick = false;
  47002. this.pinchInwards = true;
  47003. }
  47004. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47005. var _this = this;
  47006. var engine = this.camera.getEngine();
  47007. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47008. var pointA = null;
  47009. var pointB = null;
  47010. var previousPinchSquaredDistance = 0;
  47011. var initialDistance = 0;
  47012. var twoFingerActivityCount = 0;
  47013. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47014. this._pointerInput = function (p, s) {
  47015. var evt = p.event;
  47016. var isTouch = p.event.pointerType === "touch";
  47017. if (engine.isInVRExclusivePointerMode) {
  47018. return;
  47019. }
  47020. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47021. return;
  47022. }
  47023. var srcElement = (evt.srcElement || evt.target);
  47024. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47025. try {
  47026. srcElement.setPointerCapture(evt.pointerId);
  47027. }
  47028. catch (e) {
  47029. //Nothing to do with the error. Execution will continue.
  47030. }
  47031. // Manage panning with pan button click
  47032. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47033. // manage pointers
  47034. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47035. if (pointA === null) {
  47036. pointA = cacheSoloPointer;
  47037. }
  47038. else if (pointB === null) {
  47039. pointB = cacheSoloPointer;
  47040. }
  47041. if (!noPreventDefault) {
  47042. evt.preventDefault();
  47043. element.focus();
  47044. }
  47045. }
  47046. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47047. _this.camera.restoreState();
  47048. }
  47049. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47050. try {
  47051. srcElement.releasePointerCapture(evt.pointerId);
  47052. }
  47053. catch (e) {
  47054. //Nothing to do with the error.
  47055. }
  47056. cacheSoloPointer = null;
  47057. previousPinchSquaredDistance = 0;
  47058. previousMultiTouchPanPosition.isPaning = false;
  47059. previousMultiTouchPanPosition.isPinching = false;
  47060. twoFingerActivityCount = 0;
  47061. initialDistance = 0;
  47062. if (!isTouch) {
  47063. pointB = null; // Mouse and pen are mono pointer
  47064. }
  47065. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47066. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47067. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47068. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47069. if (engine._badOS) {
  47070. pointA = pointB = null;
  47071. }
  47072. else {
  47073. //only remove the impacted pointer in case of multitouch allowing on most
  47074. //platforms switching from rotate to zoom and pan seamlessly.
  47075. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47076. pointA = pointB;
  47077. pointB = null;
  47078. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47079. }
  47080. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47081. pointB = null;
  47082. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47083. }
  47084. else {
  47085. pointA = pointB = null;
  47086. }
  47087. }
  47088. if (!noPreventDefault) {
  47089. evt.preventDefault();
  47090. }
  47091. }
  47092. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47093. if (!noPreventDefault) {
  47094. evt.preventDefault();
  47095. }
  47096. // One button down
  47097. if (pointA && pointB === null && cacheSoloPointer) {
  47098. if (_this.panningSensibility !== 0 &&
  47099. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47100. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47101. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47102. }
  47103. else {
  47104. var offsetX = evt.clientX - cacheSoloPointer.x;
  47105. var offsetY = evt.clientY - cacheSoloPointer.y;
  47106. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47107. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47108. }
  47109. cacheSoloPointer.x = evt.clientX;
  47110. cacheSoloPointer.y = evt.clientY;
  47111. }
  47112. // Two buttons down: pinch/pan
  47113. else if (pointA && pointB) {
  47114. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47115. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47116. ed.x = evt.clientX;
  47117. ed.y = evt.clientY;
  47118. var direction = _this.pinchInwards ? 1 : -1;
  47119. var distX = pointA.x - pointB.x;
  47120. var distY = pointA.y - pointB.y;
  47121. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47122. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47123. if (previousPinchSquaredDistance === 0) {
  47124. initialDistance = pinchDistance;
  47125. previousPinchSquaredDistance = pinchSquaredDistance;
  47126. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47127. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47128. return;
  47129. }
  47130. if (_this.multiTouchPanAndZoom) {
  47131. if (_this.pinchDeltaPercentage) {
  47132. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47133. }
  47134. else {
  47135. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47136. (_this.pinchPrecision *
  47137. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47138. direction);
  47139. }
  47140. if (_this.panningSensibility !== 0) {
  47141. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47142. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47143. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47144. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47145. previousMultiTouchPanPosition.x = pointersCenterX;
  47146. previousMultiTouchPanPosition.y = pointersCenterY;
  47147. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47148. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47149. }
  47150. }
  47151. else {
  47152. twoFingerActivityCount++;
  47153. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47154. if (_this.pinchDeltaPercentage) {
  47155. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47156. }
  47157. else {
  47158. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47159. (_this.pinchPrecision *
  47160. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47161. direction);
  47162. }
  47163. previousMultiTouchPanPosition.isPaning = false;
  47164. previousMultiTouchPanPosition.isPinching = true;
  47165. }
  47166. else {
  47167. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47168. if (!previousMultiTouchPanPosition.isPaning) {
  47169. previousMultiTouchPanPosition.isPaning = true;
  47170. previousMultiTouchPanPosition.isPinching = false;
  47171. previousMultiTouchPanPosition.x = ed.x;
  47172. previousMultiTouchPanPosition.y = ed.y;
  47173. return;
  47174. }
  47175. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47176. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47177. }
  47178. }
  47179. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47180. previousMultiTouchPanPosition.x = ed.x;
  47181. previousMultiTouchPanPosition.y = ed.y;
  47182. }
  47183. }
  47184. previousPinchSquaredDistance = pinchSquaredDistance;
  47185. }
  47186. }
  47187. };
  47188. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47189. this._onContextMenu = function (evt) {
  47190. evt.preventDefault();
  47191. };
  47192. if (!this.camera._useCtrlForPanning) {
  47193. element.addEventListener("contextmenu", this._onContextMenu, false);
  47194. }
  47195. this._onLostFocus = function () {
  47196. //this._keys = [];
  47197. pointA = pointB = null;
  47198. previousPinchSquaredDistance = 0;
  47199. previousMultiTouchPanPosition.isPaning = false;
  47200. previousMultiTouchPanPosition.isPinching = false;
  47201. twoFingerActivityCount = 0;
  47202. cacheSoloPointer = null;
  47203. initialDistance = 0;
  47204. };
  47205. this._onMouseMove = function (evt) {
  47206. if (!engine.isPointerLock) {
  47207. return;
  47208. }
  47209. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47210. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47211. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47212. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47213. if (!noPreventDefault) {
  47214. evt.preventDefault();
  47215. }
  47216. };
  47217. this._onGestureStart = function (e) {
  47218. if (window.MSGesture === undefined) {
  47219. return;
  47220. }
  47221. if (!_this._MSGestureHandler) {
  47222. _this._MSGestureHandler = new MSGesture();
  47223. _this._MSGestureHandler.target = element;
  47224. }
  47225. _this._MSGestureHandler.addPointer(e.pointerId);
  47226. };
  47227. this._onGesture = function (e) {
  47228. _this.camera.radius *= e.scale;
  47229. if (e.preventDefault) {
  47230. if (!noPreventDefault) {
  47231. e.stopPropagation();
  47232. e.preventDefault();
  47233. }
  47234. }
  47235. };
  47236. element.addEventListener("mousemove", this._onMouseMove, false);
  47237. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47238. element.addEventListener("MSGestureChange", this._onGesture, false);
  47239. BABYLON.Tools.RegisterTopRootEvents([
  47240. { name: "blur", handler: this._onLostFocus }
  47241. ]);
  47242. };
  47243. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47244. if (this._onLostFocus) {
  47245. BABYLON.Tools.UnregisterTopRootEvents([
  47246. { name: "blur", handler: this._onLostFocus }
  47247. ]);
  47248. }
  47249. if (element && this._observer) {
  47250. this.camera.getScene().onPointerObservable.remove(this._observer);
  47251. this._observer = null;
  47252. if (this._onContextMenu) {
  47253. element.removeEventListener("contextmenu", this._onContextMenu);
  47254. }
  47255. if (this._onMouseMove) {
  47256. element.removeEventListener("mousemove", this._onMouseMove);
  47257. }
  47258. if (this._onGestureStart) {
  47259. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47260. }
  47261. if (this._onGesture) {
  47262. element.removeEventListener("MSGestureChange", this._onGesture);
  47263. }
  47264. this._isPanClick = false;
  47265. this.pinchInwards = true;
  47266. this._onMouseMove = null;
  47267. this._onGestureStart = null;
  47268. this._onGesture = null;
  47269. this._MSGestureHandler = null;
  47270. this._onLostFocus = null;
  47271. this._onContextMenu = null;
  47272. }
  47273. };
  47274. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47275. return "ArcRotateCameraPointersInput";
  47276. };
  47277. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47278. return "pointers";
  47279. };
  47280. __decorate([
  47281. BABYLON.serialize()
  47282. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47283. __decorate([
  47284. BABYLON.serialize()
  47285. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47286. __decorate([
  47287. BABYLON.serialize()
  47288. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47289. __decorate([
  47290. BABYLON.serialize()
  47291. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47292. __decorate([
  47293. BABYLON.serialize()
  47294. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47295. __decorate([
  47296. BABYLON.serialize()
  47297. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47298. __decorate([
  47299. BABYLON.serialize()
  47300. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47301. __decorate([
  47302. BABYLON.serialize()
  47303. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47304. return ArcRotateCameraPointersInput;
  47305. }());
  47306. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47307. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47308. })(BABYLON || (BABYLON = {}));
  47309. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47310. var BABYLON;
  47311. (function (BABYLON) {
  47312. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47313. __extends(ArcRotateCameraInputsManager, _super);
  47314. function ArcRotateCameraInputsManager(camera) {
  47315. return _super.call(this, camera) || this;
  47316. }
  47317. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47318. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47319. return this;
  47320. };
  47321. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47322. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47323. return this;
  47324. };
  47325. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47326. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47327. return this;
  47328. };
  47329. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47330. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47331. return this;
  47332. };
  47333. return ArcRotateCameraInputsManager;
  47334. }(BABYLON.CameraInputsManager));
  47335. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47336. })(BABYLON || (BABYLON = {}));
  47337. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47338. var BABYLON;
  47339. (function (BABYLON) {
  47340. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47341. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47342. });
  47343. var ArcRotateCamera = /** @class */ (function (_super) {
  47344. __extends(ArcRotateCamera, _super);
  47345. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47346. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47347. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47348. _this.inertialAlphaOffset = 0;
  47349. _this.inertialBetaOffset = 0;
  47350. _this.inertialRadiusOffset = 0;
  47351. _this.lowerAlphaLimit = null;
  47352. _this.upperAlphaLimit = null;
  47353. _this.lowerBetaLimit = 0.01;
  47354. _this.upperBetaLimit = Math.PI;
  47355. _this.lowerRadiusLimit = null;
  47356. _this.upperRadiusLimit = null;
  47357. _this.inertialPanningX = 0;
  47358. _this.inertialPanningY = 0;
  47359. _this.pinchToPanMaxDistance = 20;
  47360. _this.panningDistanceLimit = null;
  47361. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47362. _this.panningInertia = 0.9;
  47363. //-- end properties for backward compatibility for inputs
  47364. _this.zoomOnFactor = 1;
  47365. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47366. _this.allowUpsideDown = true;
  47367. _this._viewMatrix = new BABYLON.Matrix();
  47368. // Panning
  47369. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47370. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47371. _this.checkCollisions = false;
  47372. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47373. _this._previousPosition = BABYLON.Vector3.Zero();
  47374. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47375. _this._newPosition = BABYLON.Vector3.Zero();
  47376. _this._computationVector = BABYLON.Vector3.Zero();
  47377. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47378. if (collidedMesh === void 0) { collidedMesh = null; }
  47379. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47380. newPosition.multiplyInPlace(_this._collider._radius);
  47381. }
  47382. if (!collidedMesh) {
  47383. _this._previousPosition.copyFrom(_this.position);
  47384. }
  47385. else {
  47386. _this.setPosition(newPosition);
  47387. if (_this.onCollide) {
  47388. _this.onCollide(collidedMesh);
  47389. }
  47390. }
  47391. // Recompute because of constraints
  47392. var cosa = Math.cos(_this.alpha);
  47393. var sina = Math.sin(_this.alpha);
  47394. var cosb = Math.cos(_this.beta);
  47395. var sinb = Math.sin(_this.beta);
  47396. if (sinb === 0) {
  47397. sinb = 0.0001;
  47398. }
  47399. var target = _this._getTargetPosition();
  47400. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47401. target.addToRef(_this._computationVector, _this._newPosition);
  47402. _this.position.copyFrom(_this._newPosition);
  47403. var up = _this.upVector;
  47404. if (_this.allowUpsideDown && _this.beta < 0) {
  47405. up = up.clone();
  47406. up = up.negate();
  47407. }
  47408. _this._computeViewMatrix(_this.position, target, up);
  47409. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47410. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47411. _this._collisionTriggered = false;
  47412. };
  47413. _this._target = BABYLON.Vector3.Zero();
  47414. if (target) {
  47415. _this.setTarget(target);
  47416. }
  47417. _this.alpha = alpha;
  47418. _this.beta = beta;
  47419. _this.radius = radius;
  47420. _this.getViewMatrix();
  47421. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47422. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47423. return _this;
  47424. }
  47425. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47426. get: function () {
  47427. return this._target;
  47428. },
  47429. set: function (value) {
  47430. this.setTarget(value);
  47431. },
  47432. enumerable: true,
  47433. configurable: true
  47434. });
  47435. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47436. //-- begin properties for backward compatibility for inputs
  47437. get: function () {
  47438. var pointers = this.inputs.attached["pointers"];
  47439. if (pointers)
  47440. return pointers.angularSensibilityX;
  47441. return 0;
  47442. },
  47443. set: function (value) {
  47444. var pointers = this.inputs.attached["pointers"];
  47445. if (pointers) {
  47446. pointers.angularSensibilityX = value;
  47447. }
  47448. },
  47449. enumerable: true,
  47450. configurable: true
  47451. });
  47452. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47453. get: function () {
  47454. var pointers = this.inputs.attached["pointers"];
  47455. if (pointers)
  47456. return pointers.angularSensibilityY;
  47457. return 0;
  47458. },
  47459. set: function (value) {
  47460. var pointers = this.inputs.attached["pointers"];
  47461. if (pointers) {
  47462. pointers.angularSensibilityY = value;
  47463. }
  47464. },
  47465. enumerable: true,
  47466. configurable: true
  47467. });
  47468. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47469. get: function () {
  47470. var pointers = this.inputs.attached["pointers"];
  47471. if (pointers)
  47472. return pointers.pinchPrecision;
  47473. return 0;
  47474. },
  47475. set: function (value) {
  47476. var pointers = this.inputs.attached["pointers"];
  47477. if (pointers) {
  47478. pointers.pinchPrecision = value;
  47479. }
  47480. },
  47481. enumerable: true,
  47482. configurable: true
  47483. });
  47484. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47485. get: function () {
  47486. var pointers = this.inputs.attached["pointers"];
  47487. if (pointers)
  47488. return pointers.pinchDeltaPercentage;
  47489. return 0;
  47490. },
  47491. set: function (value) {
  47492. var pointers = this.inputs.attached["pointers"];
  47493. if (pointers) {
  47494. pointers.pinchDeltaPercentage = value;
  47495. }
  47496. },
  47497. enumerable: true,
  47498. configurable: true
  47499. });
  47500. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47501. get: function () {
  47502. var pointers = this.inputs.attached["pointers"];
  47503. if (pointers)
  47504. return pointers.panningSensibility;
  47505. return 0;
  47506. },
  47507. set: function (value) {
  47508. var pointers = this.inputs.attached["pointers"];
  47509. if (pointers) {
  47510. pointers.panningSensibility = value;
  47511. }
  47512. },
  47513. enumerable: true,
  47514. configurable: true
  47515. });
  47516. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47517. get: function () {
  47518. var keyboard = this.inputs.attached["keyboard"];
  47519. if (keyboard)
  47520. return keyboard.keysUp;
  47521. return [];
  47522. },
  47523. set: function (value) {
  47524. var keyboard = this.inputs.attached["keyboard"];
  47525. if (keyboard)
  47526. keyboard.keysUp = value;
  47527. },
  47528. enumerable: true,
  47529. configurable: true
  47530. });
  47531. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47532. get: function () {
  47533. var keyboard = this.inputs.attached["keyboard"];
  47534. if (keyboard)
  47535. return keyboard.keysDown;
  47536. return [];
  47537. },
  47538. set: function (value) {
  47539. var keyboard = this.inputs.attached["keyboard"];
  47540. if (keyboard)
  47541. keyboard.keysDown = value;
  47542. },
  47543. enumerable: true,
  47544. configurable: true
  47545. });
  47546. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47547. get: function () {
  47548. var keyboard = this.inputs.attached["keyboard"];
  47549. if (keyboard)
  47550. return keyboard.keysLeft;
  47551. return [];
  47552. },
  47553. set: function (value) {
  47554. var keyboard = this.inputs.attached["keyboard"];
  47555. if (keyboard)
  47556. keyboard.keysLeft = value;
  47557. },
  47558. enumerable: true,
  47559. configurable: true
  47560. });
  47561. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47562. get: function () {
  47563. var keyboard = this.inputs.attached["keyboard"];
  47564. if (keyboard)
  47565. return keyboard.keysRight;
  47566. return [];
  47567. },
  47568. set: function (value) {
  47569. var keyboard = this.inputs.attached["keyboard"];
  47570. if (keyboard)
  47571. keyboard.keysRight = value;
  47572. },
  47573. enumerable: true,
  47574. configurable: true
  47575. });
  47576. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47577. get: function () {
  47578. var mousewheel = this.inputs.attached["mousewheel"];
  47579. if (mousewheel)
  47580. return mousewheel.wheelPrecision;
  47581. return 0;
  47582. },
  47583. set: function (value) {
  47584. var mousewheel = this.inputs.attached["mousewheel"];
  47585. if (mousewheel)
  47586. mousewheel.wheelPrecision = value;
  47587. },
  47588. enumerable: true,
  47589. configurable: true
  47590. });
  47591. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47592. get: function () {
  47593. var mousewheel = this.inputs.attached["mousewheel"];
  47594. if (mousewheel)
  47595. return mousewheel.wheelDeltaPercentage;
  47596. return 0;
  47597. },
  47598. set: function (value) {
  47599. var mousewheel = this.inputs.attached["mousewheel"];
  47600. if (mousewheel)
  47601. mousewheel.wheelDeltaPercentage = value;
  47602. },
  47603. enumerable: true,
  47604. configurable: true
  47605. });
  47606. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47607. get: function () {
  47608. return this._bouncingBehavior;
  47609. },
  47610. enumerable: true,
  47611. configurable: true
  47612. });
  47613. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47614. get: function () {
  47615. return this._bouncingBehavior != null;
  47616. },
  47617. set: function (value) {
  47618. if (value === this.useBouncingBehavior) {
  47619. return;
  47620. }
  47621. if (value) {
  47622. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47623. this.addBehavior(this._bouncingBehavior);
  47624. }
  47625. else if (this._bouncingBehavior) {
  47626. this.removeBehavior(this._bouncingBehavior);
  47627. this._bouncingBehavior = null;
  47628. }
  47629. },
  47630. enumerable: true,
  47631. configurable: true
  47632. });
  47633. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47634. get: function () {
  47635. return this._framingBehavior;
  47636. },
  47637. enumerable: true,
  47638. configurable: true
  47639. });
  47640. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47641. get: function () {
  47642. return this._framingBehavior != null;
  47643. },
  47644. set: function (value) {
  47645. if (value === this.useFramingBehavior) {
  47646. return;
  47647. }
  47648. if (value) {
  47649. this._framingBehavior = new BABYLON.FramingBehavior();
  47650. this.addBehavior(this._framingBehavior);
  47651. }
  47652. else if (this._framingBehavior) {
  47653. this.removeBehavior(this._framingBehavior);
  47654. this._framingBehavior = null;
  47655. }
  47656. },
  47657. enumerable: true,
  47658. configurable: true
  47659. });
  47660. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47661. get: function () {
  47662. return this._autoRotationBehavior;
  47663. },
  47664. enumerable: true,
  47665. configurable: true
  47666. });
  47667. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47668. get: function () {
  47669. return this._autoRotationBehavior != null;
  47670. },
  47671. set: function (value) {
  47672. if (value === this.useAutoRotationBehavior) {
  47673. return;
  47674. }
  47675. if (value) {
  47676. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47677. this.addBehavior(this._autoRotationBehavior);
  47678. }
  47679. else if (this._autoRotationBehavior) {
  47680. this.removeBehavior(this._autoRotationBehavior);
  47681. this._autoRotationBehavior = null;
  47682. }
  47683. },
  47684. enumerable: true,
  47685. configurable: true
  47686. });
  47687. // Cache
  47688. ArcRotateCamera.prototype._initCache = function () {
  47689. _super.prototype._initCache.call(this);
  47690. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47691. this._cache.alpha = undefined;
  47692. this._cache.beta = undefined;
  47693. this._cache.radius = undefined;
  47694. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47695. };
  47696. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47697. if (!ignoreParentClass) {
  47698. _super.prototype._updateCache.call(this);
  47699. }
  47700. this._cache._target.copyFrom(this._getTargetPosition());
  47701. this._cache.alpha = this.alpha;
  47702. this._cache.beta = this.beta;
  47703. this._cache.radius = this.radius;
  47704. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47705. };
  47706. ArcRotateCamera.prototype._getTargetPosition = function () {
  47707. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47708. var pos = this._targetHost.getAbsolutePosition();
  47709. if (this._targetBoundingCenter) {
  47710. pos.addToRef(this._targetBoundingCenter, this._target);
  47711. }
  47712. else {
  47713. this._target.copyFrom(pos);
  47714. }
  47715. }
  47716. var lockedTargetPosition = this._getLockedTargetPosition();
  47717. if (lockedTargetPosition) {
  47718. return lockedTargetPosition;
  47719. }
  47720. return this._target;
  47721. };
  47722. ArcRotateCamera.prototype.storeState = function () {
  47723. this._storedAlpha = this.alpha;
  47724. this._storedBeta = this.beta;
  47725. this._storedRadius = this.radius;
  47726. this._storedTarget = this._getTargetPosition().clone();
  47727. return _super.prototype.storeState.call(this);
  47728. };
  47729. /**
  47730. * Restored camera state. You must call storeState() first
  47731. */
  47732. ArcRotateCamera.prototype._restoreStateValues = function () {
  47733. if (!_super.prototype._restoreStateValues.call(this)) {
  47734. return false;
  47735. }
  47736. this.alpha = this._storedAlpha;
  47737. this.beta = this._storedBeta;
  47738. this.radius = this._storedRadius;
  47739. this.setTarget(this._storedTarget.clone());
  47740. this.inertialAlphaOffset = 0;
  47741. this.inertialBetaOffset = 0;
  47742. this.inertialRadiusOffset = 0;
  47743. this.inertialPanningX = 0;
  47744. this.inertialPanningY = 0;
  47745. return true;
  47746. };
  47747. // Synchronized
  47748. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47749. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47750. return false;
  47751. return this._cache._target.equals(this._getTargetPosition())
  47752. && this._cache.alpha === this.alpha
  47753. && this._cache.beta === this.beta
  47754. && this._cache.radius === this.radius
  47755. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47756. };
  47757. // Methods
  47758. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47759. var _this = this;
  47760. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47761. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47762. this._useCtrlForPanning = useCtrlForPanning;
  47763. this._panningMouseButton = panningMouseButton;
  47764. this.inputs.attachElement(element, noPreventDefault);
  47765. this._reset = function () {
  47766. _this.inertialAlphaOffset = 0;
  47767. _this.inertialBetaOffset = 0;
  47768. _this.inertialRadiusOffset = 0;
  47769. _this.inertialPanningX = 0;
  47770. _this.inertialPanningY = 0;
  47771. };
  47772. };
  47773. ArcRotateCamera.prototype.detachControl = function (element) {
  47774. this.inputs.detachElement(element);
  47775. if (this._reset) {
  47776. this._reset();
  47777. }
  47778. };
  47779. ArcRotateCamera.prototype._checkInputs = function () {
  47780. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47781. if (this._collisionTriggered) {
  47782. return;
  47783. }
  47784. this.inputs.checkInputs();
  47785. // Inertia
  47786. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47787. var inertialAlphaOffset = this.inertialAlphaOffset;
  47788. if (this.beta <= 0)
  47789. inertialAlphaOffset *= -1;
  47790. if (this.getScene().useRightHandedSystem)
  47791. inertialAlphaOffset *= -1;
  47792. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47793. inertialAlphaOffset *= -1;
  47794. this.alpha += inertialAlphaOffset;
  47795. this.beta += this.inertialBetaOffset;
  47796. this.radius -= this.inertialRadiusOffset;
  47797. this.inertialAlphaOffset *= this.inertia;
  47798. this.inertialBetaOffset *= this.inertia;
  47799. this.inertialRadiusOffset *= this.inertia;
  47800. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47801. this.inertialAlphaOffset = 0;
  47802. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47803. this.inertialBetaOffset = 0;
  47804. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47805. this.inertialRadiusOffset = 0;
  47806. }
  47807. // Panning inertia
  47808. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47809. if (!this._localDirection) {
  47810. this._localDirection = BABYLON.Vector3.Zero();
  47811. this._transformedDirection = BABYLON.Vector3.Zero();
  47812. }
  47813. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47814. this._localDirection.multiplyInPlace(this.panningAxis);
  47815. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47816. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47817. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47818. if (!this.panningAxis.y) {
  47819. this._transformedDirection.y = 0;
  47820. }
  47821. if (!this._targetHost) {
  47822. if (this.panningDistanceLimit) {
  47823. this._transformedDirection.addInPlace(this._target);
  47824. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47825. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47826. this._target.copyFrom(this._transformedDirection);
  47827. }
  47828. }
  47829. else {
  47830. this._target.addInPlace(this._transformedDirection);
  47831. }
  47832. }
  47833. this.inertialPanningX *= this.panningInertia;
  47834. this.inertialPanningY *= this.panningInertia;
  47835. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47836. this.inertialPanningX = 0;
  47837. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47838. this.inertialPanningY = 0;
  47839. }
  47840. // Limits
  47841. this._checkLimits();
  47842. _super.prototype._checkInputs.call(this);
  47843. };
  47844. ArcRotateCamera.prototype._checkLimits = function () {
  47845. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47846. if (this.allowUpsideDown && this.beta > Math.PI) {
  47847. this.beta = this.beta - (2 * Math.PI);
  47848. }
  47849. }
  47850. else {
  47851. if (this.beta < this.lowerBetaLimit) {
  47852. this.beta = this.lowerBetaLimit;
  47853. }
  47854. }
  47855. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47856. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47857. this.beta = this.beta + (2 * Math.PI);
  47858. }
  47859. }
  47860. else {
  47861. if (this.beta > this.upperBetaLimit) {
  47862. this.beta = this.upperBetaLimit;
  47863. }
  47864. }
  47865. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47866. this.alpha = this.lowerAlphaLimit;
  47867. }
  47868. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47869. this.alpha = this.upperAlphaLimit;
  47870. }
  47871. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47872. this.radius = this.lowerRadiusLimit;
  47873. }
  47874. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47875. this.radius = this.upperRadiusLimit;
  47876. }
  47877. };
  47878. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47879. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47880. this.radius = this._computationVector.length();
  47881. if (this.radius === 0) {
  47882. this.radius = 0.0001; // Just to avoid division by zero
  47883. }
  47884. // Alpha
  47885. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47886. if (this._computationVector.z < 0) {
  47887. this.alpha = 2 * Math.PI - this.alpha;
  47888. }
  47889. // Beta
  47890. this.beta = Math.acos(this._computationVector.y / this.radius);
  47891. this._checkLimits();
  47892. };
  47893. ArcRotateCamera.prototype.setPosition = function (position) {
  47894. if (this.position.equals(position)) {
  47895. return;
  47896. }
  47897. this.position.copyFrom(position);
  47898. this.rebuildAnglesAndRadius();
  47899. };
  47900. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47901. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47902. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47903. if (target.getBoundingInfo) {
  47904. if (toBoundingCenter) {
  47905. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47906. }
  47907. else {
  47908. this._targetBoundingCenter = null;
  47909. }
  47910. this._targetHost = target;
  47911. this._target = this._getTargetPosition();
  47912. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47913. }
  47914. else {
  47915. var newTarget = target;
  47916. var currentTarget = this._getTargetPosition();
  47917. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47918. return;
  47919. }
  47920. this._targetHost = null;
  47921. this._target = newTarget;
  47922. this._targetBoundingCenter = null;
  47923. this.onMeshTargetChangedObservable.notifyObservers(null);
  47924. }
  47925. this.rebuildAnglesAndRadius();
  47926. };
  47927. ArcRotateCamera.prototype._getViewMatrix = function () {
  47928. // Compute
  47929. var cosa = Math.cos(this.alpha);
  47930. var sina = Math.sin(this.alpha);
  47931. var cosb = Math.cos(this.beta);
  47932. var sinb = Math.sin(this.beta);
  47933. if (sinb === 0) {
  47934. sinb = 0.0001;
  47935. }
  47936. var target = this._getTargetPosition();
  47937. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47938. target.addToRef(this._computationVector, this._newPosition);
  47939. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47940. if (!this._collider) {
  47941. this._collider = new BABYLON.Collider();
  47942. }
  47943. this._collider._radius = this.collisionRadius;
  47944. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47945. this._collisionTriggered = true;
  47946. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47947. }
  47948. else {
  47949. this.position.copyFrom(this._newPosition);
  47950. var up = this.upVector;
  47951. if (this.allowUpsideDown && sinb < 0) {
  47952. up = up.clone();
  47953. up = up.negate();
  47954. }
  47955. this._computeViewMatrix(this.position, target, up);
  47956. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47957. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47958. }
  47959. this._currentTarget = target;
  47960. return this._viewMatrix;
  47961. };
  47962. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47963. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47964. meshes = meshes || this.getScene().meshes;
  47965. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47966. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47967. this.radius = distance * this.zoomOnFactor;
  47968. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47969. };
  47970. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47971. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47972. var meshesOrMinMaxVector;
  47973. var distance;
  47974. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47975. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47976. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47977. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47978. }
  47979. else { //minMaxVector and distance
  47980. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47981. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47982. distance = minMaxVectorAndDistance.distance;
  47983. }
  47984. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47985. if (!doNotUpdateMaxZ) {
  47986. this.maxZ = distance * 2;
  47987. }
  47988. };
  47989. /**
  47990. * @override
  47991. * Override Camera.createRigCamera
  47992. */
  47993. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47994. var alphaShift = 0;
  47995. switch (this.cameraRigMode) {
  47996. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47997. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47998. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47999. case BABYLON.Camera.RIG_MODE_VR:
  48000. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48001. break;
  48002. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48003. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48004. break;
  48005. }
  48006. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48007. rigCam._cameraRigParams = {};
  48008. return rigCam;
  48009. };
  48010. /**
  48011. * @override
  48012. * Override Camera._updateRigCameras
  48013. */
  48014. ArcRotateCamera.prototype._updateRigCameras = function () {
  48015. var camLeft = this._rigCameras[0];
  48016. var camRight = this._rigCameras[1];
  48017. camLeft.beta = camRight.beta = this.beta;
  48018. camLeft.radius = camRight.radius = this.radius;
  48019. switch (this.cameraRigMode) {
  48020. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48021. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48022. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48023. case BABYLON.Camera.RIG_MODE_VR:
  48024. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48025. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48026. break;
  48027. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48028. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48029. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48030. break;
  48031. }
  48032. _super.prototype._updateRigCameras.call(this);
  48033. };
  48034. ArcRotateCamera.prototype.dispose = function () {
  48035. this.inputs.clear();
  48036. _super.prototype.dispose.call(this);
  48037. };
  48038. ArcRotateCamera.prototype.getClassName = function () {
  48039. return "ArcRotateCamera";
  48040. };
  48041. __decorate([
  48042. BABYLON.serialize()
  48043. ], ArcRotateCamera.prototype, "alpha", void 0);
  48044. __decorate([
  48045. BABYLON.serialize()
  48046. ], ArcRotateCamera.prototype, "beta", void 0);
  48047. __decorate([
  48048. BABYLON.serialize()
  48049. ], ArcRotateCamera.prototype, "radius", void 0);
  48050. __decorate([
  48051. BABYLON.serializeAsVector3("target")
  48052. ], ArcRotateCamera.prototype, "_target", void 0);
  48053. __decorate([
  48054. BABYLON.serialize()
  48055. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48056. __decorate([
  48057. BABYLON.serialize()
  48058. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48059. __decorate([
  48060. BABYLON.serialize()
  48061. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48062. __decorate([
  48063. BABYLON.serialize()
  48064. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48065. __decorate([
  48066. BABYLON.serialize()
  48067. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48068. __decorate([
  48069. BABYLON.serialize()
  48070. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48071. __decorate([
  48072. BABYLON.serialize()
  48073. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48074. __decorate([
  48075. BABYLON.serialize()
  48076. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48077. __decorate([
  48078. BABYLON.serialize()
  48079. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48080. __decorate([
  48081. BABYLON.serialize()
  48082. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48083. __decorate([
  48084. BABYLON.serialize()
  48085. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48086. __decorate([
  48087. BABYLON.serialize()
  48088. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48089. __decorate([
  48090. BABYLON.serialize()
  48091. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48092. __decorate([
  48093. BABYLON.serializeAsVector3()
  48094. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48095. __decorate([
  48096. BABYLON.serialize()
  48097. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48098. __decorate([
  48099. BABYLON.serialize()
  48100. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48101. __decorate([
  48102. BABYLON.serialize()
  48103. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48104. return ArcRotateCamera;
  48105. }(BABYLON.TargetCamera));
  48106. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48107. })(BABYLON || (BABYLON = {}));
  48108. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48109. var BABYLON;
  48110. (function (BABYLON) {
  48111. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48112. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48113. });
  48114. /**
  48115. * The HemisphericLight simulates the ambient environment light,
  48116. * so the passed direction is the light reflection direction, not the incoming direction.
  48117. */
  48118. var HemisphericLight = /** @class */ (function (_super) {
  48119. __extends(HemisphericLight, _super);
  48120. /**
  48121. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48122. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48123. * The HemisphericLight can't cast shadows.
  48124. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48125. * @param name The friendly name of the light
  48126. * @param direction The direction of the light reflection
  48127. * @param scene The scene the light belongs to
  48128. */
  48129. function HemisphericLight(name, direction, scene) {
  48130. var _this = _super.call(this, name, scene) || this;
  48131. /**
  48132. * The groundColor is the light in the opposite direction to the one specified during creation.
  48133. * 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.
  48134. */
  48135. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48136. _this.direction = direction || BABYLON.Vector3.Up();
  48137. return _this;
  48138. }
  48139. HemisphericLight.prototype._buildUniformLayout = function () {
  48140. this._uniformBuffer.addUniform("vLightData", 4);
  48141. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48142. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48143. this._uniformBuffer.addUniform("vLightGround", 3);
  48144. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48145. this._uniformBuffer.addUniform("depthValues", 2);
  48146. this._uniformBuffer.create();
  48147. };
  48148. /**
  48149. * Returns the string "HemisphericLight".
  48150. * @return The class name
  48151. */
  48152. HemisphericLight.prototype.getClassName = function () {
  48153. return "HemisphericLight";
  48154. };
  48155. /**
  48156. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48157. * Returns the updated direction.
  48158. * @param target The target the direction should point to
  48159. * @return The computed direction
  48160. */
  48161. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48162. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48163. return this.direction;
  48164. };
  48165. /**
  48166. * Returns the shadow generator associated to the light.
  48167. * @returns Always null for hemispheric lights because it does not support shadows.
  48168. */
  48169. HemisphericLight.prototype.getShadowGenerator = function () {
  48170. return null;
  48171. };
  48172. /**
  48173. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48174. * @param effect The effect to update
  48175. * @param lightIndex The index of the light in the effect to update
  48176. * @returns The hemispheric light
  48177. */
  48178. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48179. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48180. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48181. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48182. return this;
  48183. };
  48184. /**
  48185. * @hidden internal use only.
  48186. */
  48187. HemisphericLight.prototype._getWorldMatrix = function () {
  48188. if (!this._worldMatrix) {
  48189. this._worldMatrix = BABYLON.Matrix.Identity();
  48190. }
  48191. return this._worldMatrix;
  48192. };
  48193. /**
  48194. * Returns the integer 3.
  48195. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48196. */
  48197. HemisphericLight.prototype.getTypeID = function () {
  48198. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48199. };
  48200. /**
  48201. * Prepares the list of defines specific to the light type.
  48202. * @param defines the list of defines
  48203. * @param lightIndex defines the index of the light for the effect
  48204. */
  48205. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48206. defines["HEMILIGHT" + lightIndex] = true;
  48207. };
  48208. __decorate([
  48209. BABYLON.serializeAsColor3()
  48210. ], HemisphericLight.prototype, "groundColor", void 0);
  48211. __decorate([
  48212. BABYLON.serializeAsVector3()
  48213. ], HemisphericLight.prototype, "direction", void 0);
  48214. return HemisphericLight;
  48215. }(BABYLON.Light));
  48216. BABYLON.HemisphericLight = HemisphericLight;
  48217. })(BABYLON || (BABYLON = {}));
  48218. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48219. var BABYLON;
  48220. (function (BABYLON) {
  48221. /**
  48222. * Base implementation IShadowLight
  48223. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48224. */
  48225. var ShadowLight = /** @class */ (function (_super) {
  48226. __extends(ShadowLight, _super);
  48227. function ShadowLight() {
  48228. var _this = _super !== null && _super.apply(this, arguments) || this;
  48229. _this._needProjectionMatrixCompute = true;
  48230. return _this;
  48231. }
  48232. ShadowLight.prototype._setPosition = function (value) {
  48233. this._position = value;
  48234. };
  48235. Object.defineProperty(ShadowLight.prototype, "position", {
  48236. /**
  48237. * Sets the position the shadow will be casted from. Also use as the light position for both
  48238. * point and spot lights.
  48239. */
  48240. get: function () {
  48241. return this._position;
  48242. },
  48243. /**
  48244. * Sets the position the shadow will be casted from. Also use as the light position for both
  48245. * point and spot lights.
  48246. */
  48247. set: function (value) {
  48248. this._setPosition(value);
  48249. },
  48250. enumerable: true,
  48251. configurable: true
  48252. });
  48253. ShadowLight.prototype._setDirection = function (value) {
  48254. this._direction = value;
  48255. };
  48256. Object.defineProperty(ShadowLight.prototype, "direction", {
  48257. /**
  48258. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48259. * Also use as the light direction on spot and directional lights.
  48260. */
  48261. get: function () {
  48262. return this._direction;
  48263. },
  48264. /**
  48265. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48266. * Also use as the light direction on spot and directional lights.
  48267. */
  48268. set: function (value) {
  48269. this._setDirection(value);
  48270. },
  48271. enumerable: true,
  48272. configurable: true
  48273. });
  48274. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48275. /**
  48276. * Gets the shadow projection clipping minimum z value.
  48277. */
  48278. get: function () {
  48279. return this._shadowMinZ;
  48280. },
  48281. /**
  48282. * Sets the shadow projection clipping minimum z value.
  48283. */
  48284. set: function (value) {
  48285. this._shadowMinZ = value;
  48286. this.forceProjectionMatrixCompute();
  48287. },
  48288. enumerable: true,
  48289. configurable: true
  48290. });
  48291. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48292. /**
  48293. * Sets the shadow projection clipping maximum z value.
  48294. */
  48295. get: function () {
  48296. return this._shadowMaxZ;
  48297. },
  48298. /**
  48299. * Gets the shadow projection clipping maximum z value.
  48300. */
  48301. set: function (value) {
  48302. this._shadowMaxZ = value;
  48303. this.forceProjectionMatrixCompute();
  48304. },
  48305. enumerable: true,
  48306. configurable: true
  48307. });
  48308. /**
  48309. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48310. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48311. */
  48312. ShadowLight.prototype.computeTransformedInformation = function () {
  48313. if (this.parent && this.parent.getWorldMatrix) {
  48314. if (!this.transformedPosition) {
  48315. this.transformedPosition = BABYLON.Vector3.Zero();
  48316. }
  48317. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48318. // In case the direction is present.
  48319. if (this.direction) {
  48320. if (!this.transformedDirection) {
  48321. this.transformedDirection = BABYLON.Vector3.Zero();
  48322. }
  48323. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48324. }
  48325. return true;
  48326. }
  48327. return false;
  48328. };
  48329. /**
  48330. * Return the depth scale used for the shadow map.
  48331. * @returns the depth scale.
  48332. */
  48333. ShadowLight.prototype.getDepthScale = function () {
  48334. return 50.0;
  48335. };
  48336. /**
  48337. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48338. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48339. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48340. */
  48341. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48342. return this.transformedDirection ? this.transformedDirection : this.direction;
  48343. };
  48344. /**
  48345. * Returns the ShadowLight absolute position in the World.
  48346. * @returns the position vector in world space
  48347. */
  48348. ShadowLight.prototype.getAbsolutePosition = function () {
  48349. return this.transformedPosition ? this.transformedPosition : this.position;
  48350. };
  48351. /**
  48352. * Sets the ShadowLight direction toward the passed target.
  48353. * @param target The point tot target in local space
  48354. * @returns the updated ShadowLight direction
  48355. */
  48356. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48357. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48358. return this.direction;
  48359. };
  48360. /**
  48361. * Returns the light rotation in euler definition.
  48362. * @returns the x y z rotation in local space.
  48363. */
  48364. ShadowLight.prototype.getRotation = function () {
  48365. this.direction.normalize();
  48366. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48367. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48368. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48369. };
  48370. /**
  48371. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48372. * @returns true if a cube texture needs to be use
  48373. */
  48374. ShadowLight.prototype.needCube = function () {
  48375. return false;
  48376. };
  48377. /**
  48378. * Detects if the projection matrix requires to be recomputed this frame.
  48379. * @returns true if it requires to be recomputed otherwise, false.
  48380. */
  48381. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48382. return this._needProjectionMatrixCompute;
  48383. };
  48384. /**
  48385. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48386. */
  48387. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48388. this._needProjectionMatrixCompute = true;
  48389. };
  48390. /**
  48391. * Get the world matrix of the sahdow lights.
  48392. * @hidden Internal Use Only
  48393. */
  48394. ShadowLight.prototype._getWorldMatrix = function () {
  48395. if (!this._worldMatrix) {
  48396. this._worldMatrix = BABYLON.Matrix.Identity();
  48397. }
  48398. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48399. return this._worldMatrix;
  48400. };
  48401. /**
  48402. * Gets the minZ used for shadow according to both the scene and the light.
  48403. * @param activeCamera The camera we are returning the min for
  48404. * @returns the depth min z
  48405. */
  48406. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48407. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48408. };
  48409. /**
  48410. * Gets the maxZ used for shadow according to both the scene and the light.
  48411. * @param activeCamera The camera we are returning the max for
  48412. * @returns the depth max z
  48413. */
  48414. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48415. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48416. };
  48417. /**
  48418. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48419. * @param matrix The materix to updated with the projection information
  48420. * @param viewMatrix The transform matrix of the light
  48421. * @param renderList The list of mesh to render in the map
  48422. * @returns The current light
  48423. */
  48424. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48425. if (this.customProjectionMatrixBuilder) {
  48426. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48427. }
  48428. else {
  48429. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48430. }
  48431. return this;
  48432. };
  48433. __decorate([
  48434. BABYLON.serializeAsVector3()
  48435. ], ShadowLight.prototype, "position", null);
  48436. __decorate([
  48437. BABYLON.serializeAsVector3()
  48438. ], ShadowLight.prototype, "direction", null);
  48439. __decorate([
  48440. BABYLON.serialize()
  48441. ], ShadowLight.prototype, "shadowMinZ", null);
  48442. __decorate([
  48443. BABYLON.serialize()
  48444. ], ShadowLight.prototype, "shadowMaxZ", null);
  48445. return ShadowLight;
  48446. }(BABYLON.Light));
  48447. BABYLON.ShadowLight = ShadowLight;
  48448. })(BABYLON || (BABYLON = {}));
  48449. //# sourceMappingURL=babylon.shadowLight.js.map
  48450. var BABYLON;
  48451. (function (BABYLON) {
  48452. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48453. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48454. });
  48455. /**
  48456. * A point light is a light defined by an unique point in world space.
  48457. * The light is emitted in every direction from this point.
  48458. * A good example of a point light is a standard light bulb.
  48459. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48460. */
  48461. var PointLight = /** @class */ (function (_super) {
  48462. __extends(PointLight, _super);
  48463. /**
  48464. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48465. * A PointLight emits the light in every direction.
  48466. * It can cast shadows.
  48467. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48468. * ```javascript
  48469. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48470. * ```
  48471. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48472. * @param name The light friendly name
  48473. * @param position The position of the point light in the scene
  48474. * @param scene The scene the lights belongs to
  48475. */
  48476. function PointLight(name, position, scene) {
  48477. var _this = _super.call(this, name, scene) || this;
  48478. _this._shadowAngle = Math.PI / 2;
  48479. _this.position = position;
  48480. return _this;
  48481. }
  48482. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48483. /**
  48484. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48485. * This specifies what angle the shadow will use to be created.
  48486. *
  48487. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48488. */
  48489. get: function () {
  48490. return this._shadowAngle;
  48491. },
  48492. /**
  48493. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48494. * This specifies what angle the shadow will use to be created.
  48495. *
  48496. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48497. */
  48498. set: function (value) {
  48499. this._shadowAngle = value;
  48500. this.forceProjectionMatrixCompute();
  48501. },
  48502. enumerable: true,
  48503. configurable: true
  48504. });
  48505. Object.defineProperty(PointLight.prototype, "direction", {
  48506. /**
  48507. * Gets the direction if it has been set.
  48508. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48509. */
  48510. get: function () {
  48511. return this._direction;
  48512. },
  48513. /**
  48514. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48515. */
  48516. set: function (value) {
  48517. var previousNeedCube = this.needCube();
  48518. this._direction = value;
  48519. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48520. this._shadowGenerator.recreateShadowMap();
  48521. }
  48522. },
  48523. enumerable: true,
  48524. configurable: true
  48525. });
  48526. /**
  48527. * Returns the string "PointLight"
  48528. * @returns the class name
  48529. */
  48530. PointLight.prototype.getClassName = function () {
  48531. return "PointLight";
  48532. };
  48533. /**
  48534. * Returns the integer 0.
  48535. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48536. */
  48537. PointLight.prototype.getTypeID = function () {
  48538. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48539. };
  48540. /**
  48541. * Specifies wether or not the shadowmap should be a cube texture.
  48542. * @returns true if the shadowmap needs to be a cube texture.
  48543. */
  48544. PointLight.prototype.needCube = function () {
  48545. return !this.direction;
  48546. };
  48547. /**
  48548. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48549. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48550. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48551. */
  48552. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48553. if (this.direction) {
  48554. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48555. }
  48556. else {
  48557. switch (faceIndex) {
  48558. case 0:
  48559. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48560. case 1:
  48561. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48562. case 2:
  48563. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48564. case 3:
  48565. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48566. case 4:
  48567. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48568. case 5:
  48569. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48570. }
  48571. }
  48572. return BABYLON.Vector3.Zero();
  48573. };
  48574. /**
  48575. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48576. * - fov = PI / 2
  48577. * - aspect ratio : 1.0
  48578. * - z-near and far equal to the active camera minZ and maxZ.
  48579. * Returns the PointLight.
  48580. */
  48581. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48582. var activeCamera = this.getScene().activeCamera;
  48583. if (!activeCamera) {
  48584. return;
  48585. }
  48586. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48587. };
  48588. PointLight.prototype._buildUniformLayout = function () {
  48589. this._uniformBuffer.addUniform("vLightData", 4);
  48590. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48591. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48592. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48593. this._uniformBuffer.addUniform("depthValues", 2);
  48594. this._uniformBuffer.create();
  48595. };
  48596. /**
  48597. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48598. * @param effect The effect to update
  48599. * @param lightIndex The index of the light in the effect to update
  48600. * @returns The point light
  48601. */
  48602. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48603. if (this.computeTransformedInformation()) {
  48604. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48605. return this;
  48606. }
  48607. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48608. return this;
  48609. };
  48610. /**
  48611. * Prepares the list of defines specific to the light type.
  48612. * @param defines the list of defines
  48613. * @param lightIndex defines the index of the light for the effect
  48614. */
  48615. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48616. defines["POINTLIGHT" + lightIndex] = true;
  48617. };
  48618. __decorate([
  48619. BABYLON.serialize()
  48620. ], PointLight.prototype, "shadowAngle", null);
  48621. return PointLight;
  48622. }(BABYLON.ShadowLight));
  48623. BABYLON.PointLight = PointLight;
  48624. })(BABYLON || (BABYLON = {}));
  48625. //# sourceMappingURL=babylon.pointLight.js.map
  48626. var BABYLON;
  48627. (function (BABYLON) {
  48628. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48629. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48630. });
  48631. /**
  48632. * A directional light is defined by a direction (what a surprise!).
  48633. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48634. * 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.
  48635. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48636. */
  48637. var DirectionalLight = /** @class */ (function (_super) {
  48638. __extends(DirectionalLight, _super);
  48639. /**
  48640. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48641. * The directional light is emitted from everywhere in the given direction.
  48642. * It can cast shawdows.
  48643. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48644. * @param name The friendly name of the light
  48645. * @param direction The direction of the light
  48646. * @param scene The scene the light belongs to
  48647. */
  48648. function DirectionalLight(name, direction, scene) {
  48649. var _this = _super.call(this, name, scene) || this;
  48650. _this._shadowFrustumSize = 0;
  48651. _this._shadowOrthoScale = 0.1;
  48652. /**
  48653. * Automatically compute the projection matrix to best fit (including all the casters)
  48654. * on each frame.
  48655. */
  48656. _this.autoUpdateExtends = true;
  48657. // Cache
  48658. _this._orthoLeft = Number.MAX_VALUE;
  48659. _this._orthoRight = Number.MIN_VALUE;
  48660. _this._orthoTop = Number.MIN_VALUE;
  48661. _this._orthoBottom = Number.MAX_VALUE;
  48662. _this.position = direction.scale(-1.0);
  48663. _this.direction = direction;
  48664. return _this;
  48665. }
  48666. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48667. /**
  48668. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48669. */
  48670. get: function () {
  48671. return this._shadowFrustumSize;
  48672. },
  48673. /**
  48674. * Specifies a fix frustum size for the shadow generation.
  48675. */
  48676. set: function (value) {
  48677. this._shadowFrustumSize = value;
  48678. this.forceProjectionMatrixCompute();
  48679. },
  48680. enumerable: true,
  48681. configurable: true
  48682. });
  48683. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48684. /**
  48685. * Gets the shadow projection scale against the optimal computed one.
  48686. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48687. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48688. */
  48689. get: function () {
  48690. return this._shadowOrthoScale;
  48691. },
  48692. /**
  48693. * Sets the shadow projection scale against the optimal computed one.
  48694. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48695. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48696. */
  48697. set: function (value) {
  48698. this._shadowOrthoScale = value;
  48699. this.forceProjectionMatrixCompute();
  48700. },
  48701. enumerable: true,
  48702. configurable: true
  48703. });
  48704. /**
  48705. * Returns the string "DirectionalLight".
  48706. * @return The class name
  48707. */
  48708. DirectionalLight.prototype.getClassName = function () {
  48709. return "DirectionalLight";
  48710. };
  48711. /**
  48712. * Returns the integer 1.
  48713. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48714. */
  48715. DirectionalLight.prototype.getTypeID = function () {
  48716. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48717. };
  48718. /**
  48719. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48720. * Returns the DirectionalLight Shadow projection matrix.
  48721. */
  48722. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48723. if (this.shadowFrustumSize > 0) {
  48724. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48725. }
  48726. else {
  48727. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48728. }
  48729. };
  48730. /**
  48731. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48732. * Returns the DirectionalLight Shadow projection matrix.
  48733. */
  48734. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48735. var activeCamera = this.getScene().activeCamera;
  48736. if (!activeCamera) {
  48737. return;
  48738. }
  48739. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48740. };
  48741. /**
  48742. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48743. * Returns the DirectionalLight Shadow projection matrix.
  48744. */
  48745. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48746. var activeCamera = this.getScene().activeCamera;
  48747. if (!activeCamera) {
  48748. return;
  48749. }
  48750. // Check extends
  48751. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48752. var tempVector3 = BABYLON.Vector3.Zero();
  48753. this._orthoLeft = Number.MAX_VALUE;
  48754. this._orthoRight = Number.MIN_VALUE;
  48755. this._orthoTop = Number.MIN_VALUE;
  48756. this._orthoBottom = Number.MAX_VALUE;
  48757. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48758. var mesh = renderList[meshIndex];
  48759. if (!mesh) {
  48760. continue;
  48761. }
  48762. var boundingInfo = mesh.getBoundingInfo();
  48763. var boundingBox = boundingInfo.boundingBox;
  48764. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48765. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48766. if (tempVector3.x < this._orthoLeft)
  48767. this._orthoLeft = tempVector3.x;
  48768. if (tempVector3.y < this._orthoBottom)
  48769. this._orthoBottom = tempVector3.y;
  48770. if (tempVector3.x > this._orthoRight)
  48771. this._orthoRight = tempVector3.x;
  48772. if (tempVector3.y > this._orthoTop)
  48773. this._orthoTop = tempVector3.y;
  48774. }
  48775. }
  48776. }
  48777. var xOffset = this._orthoRight - this._orthoLeft;
  48778. var yOffset = this._orthoTop - this._orthoBottom;
  48779. 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);
  48780. };
  48781. DirectionalLight.prototype._buildUniformLayout = function () {
  48782. this._uniformBuffer.addUniform("vLightData", 4);
  48783. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48784. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48785. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48786. this._uniformBuffer.addUniform("depthValues", 2);
  48787. this._uniformBuffer.create();
  48788. };
  48789. /**
  48790. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48791. * @param effect The effect to update
  48792. * @param lightIndex The index of the light in the effect to update
  48793. * @returns The directional light
  48794. */
  48795. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48796. if (this.computeTransformedInformation()) {
  48797. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48798. return this;
  48799. }
  48800. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48801. return this;
  48802. };
  48803. /**
  48804. * Gets the minZ used for shadow according to both the scene and the light.
  48805. *
  48806. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48807. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48808. * @param activeCamera The camera we are returning the min for
  48809. * @returns the depth min z
  48810. */
  48811. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48812. return 1;
  48813. };
  48814. /**
  48815. * Gets the maxZ used for shadow according to both the scene and the light.
  48816. *
  48817. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48818. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48819. * @param activeCamera The camera we are returning the max for
  48820. * @returns the depth max z
  48821. */
  48822. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48823. return 1;
  48824. };
  48825. /**
  48826. * Prepares the list of defines specific to the light type.
  48827. * @param defines the list of defines
  48828. * @param lightIndex defines the index of the light for the effect
  48829. */
  48830. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48831. defines["DIRLIGHT" + lightIndex] = true;
  48832. };
  48833. __decorate([
  48834. BABYLON.serialize()
  48835. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48836. __decorate([
  48837. BABYLON.serialize()
  48838. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48839. __decorate([
  48840. BABYLON.serialize()
  48841. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48842. return DirectionalLight;
  48843. }(BABYLON.ShadowLight));
  48844. BABYLON.DirectionalLight = DirectionalLight;
  48845. })(BABYLON || (BABYLON = {}));
  48846. //# sourceMappingURL=babylon.directionalLight.js.map
  48847. var BABYLON;
  48848. (function (BABYLON) {
  48849. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48850. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48851. });
  48852. /**
  48853. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48854. * These values define a cone of light starting from the position, emitting toward the direction.
  48855. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48856. * and the exponent defines the speed of the decay of the light with distance (reach).
  48857. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48858. */
  48859. var SpotLight = /** @class */ (function (_super) {
  48860. __extends(SpotLight, _super);
  48861. /**
  48862. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48863. * It can cast shadows.
  48864. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48865. * @param name The light friendly name
  48866. * @param position The position of the spot light in the scene
  48867. * @param direction The direction of the light in the scene
  48868. * @param angle The cone angle of the light in Radians
  48869. * @param exponent The light decay speed with the distance from the emission spot
  48870. * @param scene The scene the lights belongs to
  48871. */
  48872. function SpotLight(name, position, direction, angle, exponent, scene) {
  48873. var _this = _super.call(this, name, scene) || this;
  48874. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48875. _this._projectionTextureLightNear = 1e-6;
  48876. _this._projectionTextureLightFar = 1000.0;
  48877. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48878. _this._projectionTextureViewLightDirty = true;
  48879. _this._projectionTextureProjectionLightDirty = true;
  48880. _this._projectionTextureDirty = true;
  48881. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48882. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48883. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48884. _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);
  48885. _this.position = position;
  48886. _this.direction = direction;
  48887. _this.angle = angle;
  48888. _this.exponent = exponent;
  48889. return _this;
  48890. }
  48891. Object.defineProperty(SpotLight.prototype, "angle", {
  48892. /**
  48893. * Gets the cone angle of the spot light in Radians.
  48894. */
  48895. get: function () {
  48896. return this._angle;
  48897. },
  48898. /**
  48899. * Sets the cone angle of the spot light in Radians.
  48900. */
  48901. set: function (value) {
  48902. this._angle = value;
  48903. this._projectionTextureProjectionLightDirty = true;
  48904. this.forceProjectionMatrixCompute();
  48905. },
  48906. enumerable: true,
  48907. configurable: true
  48908. });
  48909. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48910. /**
  48911. * Allows scaling the angle of the light for shadow generation only.
  48912. */
  48913. get: function () {
  48914. return this._shadowAngleScale;
  48915. },
  48916. /**
  48917. * Allows scaling the angle of the light for shadow generation only.
  48918. */
  48919. set: function (value) {
  48920. this._shadowAngleScale = value;
  48921. this.forceProjectionMatrixCompute();
  48922. },
  48923. enumerable: true,
  48924. configurable: true
  48925. });
  48926. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48927. /**
  48928. * Allows reading the projecton texture
  48929. */
  48930. get: function () {
  48931. return this._projectionTextureMatrix;
  48932. },
  48933. enumerable: true,
  48934. configurable: true
  48935. });
  48936. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48937. /**
  48938. * Gets the near clip of the Spotlight for texture projection.
  48939. */
  48940. get: function () {
  48941. return this._projectionTextureLightNear;
  48942. },
  48943. /**
  48944. * Sets the near clip of the Spotlight for texture projection.
  48945. */
  48946. set: function (value) {
  48947. this._projectionTextureLightNear = value;
  48948. this._projectionTextureProjectionLightDirty = true;
  48949. },
  48950. enumerable: true,
  48951. configurable: true
  48952. });
  48953. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48954. /**
  48955. * Gets the far clip of the Spotlight for texture projection.
  48956. */
  48957. get: function () {
  48958. return this._projectionTextureLightFar;
  48959. },
  48960. /**
  48961. * Sets the far clip of the Spotlight for texture projection.
  48962. */
  48963. set: function (value) {
  48964. this._projectionTextureLightFar = value;
  48965. this._projectionTextureProjectionLightDirty = true;
  48966. },
  48967. enumerable: true,
  48968. configurable: true
  48969. });
  48970. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48971. /**
  48972. * Gets the Up vector of the Spotlight for texture projection.
  48973. */
  48974. get: function () {
  48975. return this._projectionTextureUpDirection;
  48976. },
  48977. /**
  48978. * Sets the Up vector of the Spotlight for texture projection.
  48979. */
  48980. set: function (value) {
  48981. this._projectionTextureUpDirection = value;
  48982. this._projectionTextureProjectionLightDirty = true;
  48983. },
  48984. enumerable: true,
  48985. configurable: true
  48986. });
  48987. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48988. /**
  48989. * Gets the projection texture of the light.
  48990. */
  48991. get: function () {
  48992. return this._projectionTexture;
  48993. },
  48994. /**
  48995. * Sets the projection texture of the light.
  48996. */
  48997. set: function (value) {
  48998. this._projectionTexture = value;
  48999. this._projectionTextureDirty = true;
  49000. },
  49001. enumerable: true,
  49002. configurable: true
  49003. });
  49004. /**
  49005. * Returns the string "SpotLight".
  49006. * @returns the class name
  49007. */
  49008. SpotLight.prototype.getClassName = function () {
  49009. return "SpotLight";
  49010. };
  49011. /**
  49012. * Returns the integer 2.
  49013. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49014. */
  49015. SpotLight.prototype.getTypeID = function () {
  49016. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49017. };
  49018. /**
  49019. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49020. */
  49021. SpotLight.prototype._setDirection = function (value) {
  49022. _super.prototype._setDirection.call(this, value);
  49023. this._projectionTextureViewLightDirty = true;
  49024. };
  49025. /**
  49026. * Overrides the position setter to recompute the projection texture view light Matrix.
  49027. */
  49028. SpotLight.prototype._setPosition = function (value) {
  49029. _super.prototype._setPosition.call(this, value);
  49030. this._projectionTextureViewLightDirty = true;
  49031. };
  49032. /**
  49033. * 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.
  49034. * Returns the SpotLight.
  49035. */
  49036. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49037. var activeCamera = this.getScene().activeCamera;
  49038. if (!activeCamera) {
  49039. return;
  49040. }
  49041. this._shadowAngleScale = this._shadowAngleScale || 1;
  49042. var angle = this._shadowAngleScale * this._angle;
  49043. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49044. };
  49045. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49046. this._projectionTextureViewLightDirty = false;
  49047. this._projectionTextureDirty = true;
  49048. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49049. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49050. };
  49051. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49052. this._projectionTextureProjectionLightDirty = false;
  49053. this._projectionTextureDirty = true;
  49054. var light_far = this.projectionTextureLightFar;
  49055. var light_near = this.projectionTextureLightNear;
  49056. var P = light_far / (light_far - light_near);
  49057. var Q = -P * light_near;
  49058. var S = 1.0 / Math.tan(this._angle / 2.0);
  49059. var A = 1.0;
  49060. 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);
  49061. };
  49062. /**
  49063. * Main function for light texture projection matrix computing.
  49064. */
  49065. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49066. this._projectionTextureDirty = false;
  49067. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49068. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49069. };
  49070. SpotLight.prototype._buildUniformLayout = function () {
  49071. this._uniformBuffer.addUniform("vLightData", 4);
  49072. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49073. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49074. this._uniformBuffer.addUniform("vLightDirection", 3);
  49075. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49076. this._uniformBuffer.addUniform("depthValues", 2);
  49077. this._uniformBuffer.create();
  49078. };
  49079. /**
  49080. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49081. * @param effect The effect to update
  49082. * @param lightIndex The index of the light in the effect to update
  49083. * @returns The spot light
  49084. */
  49085. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49086. var normalizeDirection;
  49087. if (this.computeTransformedInformation()) {
  49088. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49089. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49090. }
  49091. else {
  49092. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49093. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49094. }
  49095. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49096. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49097. if (this._projectionTextureViewLightDirty) {
  49098. this._computeProjectionTextureViewLightMatrix();
  49099. }
  49100. if (this._projectionTextureProjectionLightDirty) {
  49101. this._computeProjectionTextureProjectionLightMatrix();
  49102. }
  49103. if (this._projectionTextureDirty) {
  49104. this._computeProjectionTextureMatrix();
  49105. }
  49106. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49107. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49108. }
  49109. return this;
  49110. };
  49111. /**
  49112. * Disposes the light and the associated resources.
  49113. */
  49114. SpotLight.prototype.dispose = function () {
  49115. _super.prototype.dispose.call(this);
  49116. if (this._projectionTexture) {
  49117. this._projectionTexture.dispose();
  49118. }
  49119. };
  49120. /**
  49121. * Prepares the list of defines specific to the light type.
  49122. * @param defines the list of defines
  49123. * @param lightIndex defines the index of the light for the effect
  49124. */
  49125. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49126. defines["SPOTLIGHT" + lightIndex] = true;
  49127. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49128. };
  49129. __decorate([
  49130. BABYLON.serialize()
  49131. ], SpotLight.prototype, "angle", null);
  49132. __decorate([
  49133. BABYLON.serialize()
  49134. ], SpotLight.prototype, "shadowAngleScale", null);
  49135. __decorate([
  49136. BABYLON.serialize()
  49137. ], SpotLight.prototype, "exponent", void 0);
  49138. __decorate([
  49139. BABYLON.serialize()
  49140. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49141. __decorate([
  49142. BABYLON.serialize()
  49143. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49144. __decorate([
  49145. BABYLON.serialize()
  49146. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49147. __decorate([
  49148. BABYLON.serializeAsTexture("projectedLightTexture")
  49149. ], SpotLight.prototype, "_projectionTexture", void 0);
  49150. return SpotLight;
  49151. }(BABYLON.ShadowLight));
  49152. BABYLON.SpotLight = SpotLight;
  49153. })(BABYLON || (BABYLON = {}));
  49154. //# sourceMappingURL=babylon.spotLight.js.map
  49155. var BABYLON;
  49156. (function (BABYLON) {
  49157. /**
  49158. * Class used to override all child animations of a given target
  49159. */
  49160. var AnimationPropertiesOverride = /** @class */ (function () {
  49161. function AnimationPropertiesOverride() {
  49162. /**
  49163. * Gets or sets a value indicating if animation blending must be used
  49164. */
  49165. this.enableBlending = false;
  49166. /**
  49167. * Gets or sets the blending speed to use when enableBlending is true
  49168. */
  49169. this.blendingSpeed = 0.01;
  49170. /**
  49171. * Gets or sets the default loop mode to use
  49172. */
  49173. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49174. }
  49175. return AnimationPropertiesOverride;
  49176. }());
  49177. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49178. })(BABYLON || (BABYLON = {}));
  49179. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49180. var BABYLON;
  49181. (function (BABYLON) {
  49182. /**
  49183. * Represents the range of an animation
  49184. */
  49185. var AnimationRange = /** @class */ (function () {
  49186. /**
  49187. * Initializes the range of an animation
  49188. * @param name The name of the animation range
  49189. * @param from The starting frame of the animation
  49190. * @param to The ending frame of the animation
  49191. */
  49192. function AnimationRange(
  49193. /**The name of the animation range**/
  49194. name,
  49195. /**The starting frame of the animation */
  49196. from,
  49197. /**The ending frame of the animation*/
  49198. to) {
  49199. this.name = name;
  49200. this.from = from;
  49201. this.to = to;
  49202. }
  49203. /**
  49204. * Makes a copy of the animation range
  49205. * @returns A copy of the animation range
  49206. */
  49207. AnimationRange.prototype.clone = function () {
  49208. return new AnimationRange(this.name, this.from, this.to);
  49209. };
  49210. return AnimationRange;
  49211. }());
  49212. BABYLON.AnimationRange = AnimationRange;
  49213. /**
  49214. * Composed of a frame, and an action function
  49215. */
  49216. var AnimationEvent = /** @class */ (function () {
  49217. /**
  49218. * Initializes the animation event
  49219. * @param frame The frame for which the event is triggered
  49220. * @param action The event to perform when triggered
  49221. * @param onlyOnce Specifies if the event should be triggered only once
  49222. */
  49223. function AnimationEvent(
  49224. /** The frame for which the event is triggered **/
  49225. frame,
  49226. /** The event to perform when triggered **/
  49227. action,
  49228. /** Specifies if the event should be triggered only once**/
  49229. onlyOnce) {
  49230. this.frame = frame;
  49231. this.action = action;
  49232. this.onlyOnce = onlyOnce;
  49233. /**
  49234. * Specifies if the animation event is done
  49235. */
  49236. this.isDone = false;
  49237. }
  49238. /** @hidden */
  49239. AnimationEvent.prototype._clone = function () {
  49240. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49241. };
  49242. return AnimationEvent;
  49243. }());
  49244. BABYLON.AnimationEvent = AnimationEvent;
  49245. /**
  49246. * A cursor which tracks a point on a path
  49247. */
  49248. var PathCursor = /** @class */ (function () {
  49249. /**
  49250. * Initializes the path cursor
  49251. * @param path The path to track
  49252. */
  49253. function PathCursor(path) {
  49254. this.path = path;
  49255. /**
  49256. * Stores path cursor callbacks for when an onchange event is triggered
  49257. */
  49258. this._onchange = new Array();
  49259. /**
  49260. * The value of the path cursor
  49261. */
  49262. this.value = 0;
  49263. /**
  49264. * The animation array of the path cursor
  49265. */
  49266. this.animations = new Array();
  49267. }
  49268. /**
  49269. * Gets the cursor point on the path
  49270. * @returns A point on the path cursor at the cursor location
  49271. */
  49272. PathCursor.prototype.getPoint = function () {
  49273. var point = this.path.getPointAtLengthPosition(this.value);
  49274. return new BABYLON.Vector3(point.x, 0, point.y);
  49275. };
  49276. /**
  49277. * Moves the cursor ahead by the step amount
  49278. * @param step The amount to move the cursor forward
  49279. * @returns This path cursor
  49280. */
  49281. PathCursor.prototype.moveAhead = function (step) {
  49282. if (step === void 0) { step = 0.002; }
  49283. this.move(step);
  49284. return this;
  49285. };
  49286. /**
  49287. * Moves the cursor behind by the step amount
  49288. * @param step The amount to move the cursor back
  49289. * @returns This path cursor
  49290. */
  49291. PathCursor.prototype.moveBack = function (step) {
  49292. if (step === void 0) { step = 0.002; }
  49293. this.move(-step);
  49294. return this;
  49295. };
  49296. /**
  49297. * Moves the cursor by the step amount
  49298. * If the step amount is greater than one, an exception is thrown
  49299. * @param step The amount to move the cursor
  49300. * @returns This path cursor
  49301. */
  49302. PathCursor.prototype.move = function (step) {
  49303. if (Math.abs(step) > 1) {
  49304. throw "step size should be less than 1.";
  49305. }
  49306. this.value += step;
  49307. this.ensureLimits();
  49308. this.raiseOnChange();
  49309. return this;
  49310. };
  49311. /**
  49312. * Ensures that the value is limited between zero and one
  49313. * @returns This path cursor
  49314. */
  49315. PathCursor.prototype.ensureLimits = function () {
  49316. while (this.value > 1) {
  49317. this.value -= 1;
  49318. }
  49319. while (this.value < 0) {
  49320. this.value += 1;
  49321. }
  49322. return this;
  49323. };
  49324. /**
  49325. * Runs onchange callbacks on change (used by the animation engine)
  49326. * @returns This path cursor
  49327. */
  49328. PathCursor.prototype.raiseOnChange = function () {
  49329. var _this = this;
  49330. this._onchange.forEach(function (f) { return f(_this); });
  49331. return this;
  49332. };
  49333. /**
  49334. * Executes a function on change
  49335. * @param f A path cursor onchange callback
  49336. * @returns This path cursor
  49337. */
  49338. PathCursor.prototype.onchange = function (f) {
  49339. this._onchange.push(f);
  49340. return this;
  49341. };
  49342. return PathCursor;
  49343. }());
  49344. BABYLON.PathCursor = PathCursor;
  49345. /**
  49346. * Enum for the animation key frame interpolation type
  49347. */
  49348. var AnimationKeyInterpolation;
  49349. (function (AnimationKeyInterpolation) {
  49350. /**
  49351. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49352. */
  49353. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49354. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49355. /**
  49356. * Class used to store any kind of animation
  49357. */
  49358. var Animation = /** @class */ (function () {
  49359. /**
  49360. * Initializes the animation
  49361. * @param name Name of the animation
  49362. * @param targetProperty Property to animate
  49363. * @param framePerSecond The frames per second of the animation
  49364. * @param dataType The data type of the animation
  49365. * @param loopMode The loop mode of the animation
  49366. * @param enableBlendings Specifies if blending should be enabled
  49367. */
  49368. function Animation(
  49369. /**Name of the animation */
  49370. name,
  49371. /**Property to animate */
  49372. targetProperty,
  49373. /**The frames per second of the animation */
  49374. framePerSecond,
  49375. /**The data type of the animation */
  49376. dataType,
  49377. /**The loop mode of the animation */
  49378. loopMode,
  49379. /**Specifies if blending should be enabled */
  49380. enableBlending) {
  49381. this.name = name;
  49382. this.targetProperty = targetProperty;
  49383. this.framePerSecond = framePerSecond;
  49384. this.dataType = dataType;
  49385. this.loopMode = loopMode;
  49386. this.enableBlending = enableBlending;
  49387. /**
  49388. * @hidden Internal use only
  49389. */
  49390. this._runtimeAnimations = new Array();
  49391. /**
  49392. * The set of event that will be linked to this animation
  49393. */
  49394. this._events = new Array();
  49395. /**
  49396. * Stores the blending speed of the animation
  49397. */
  49398. this.blendingSpeed = 0.01;
  49399. /**
  49400. * Stores the animation ranges for the animation
  49401. */
  49402. this._ranges = {};
  49403. this.targetPropertyPath = targetProperty.split(".");
  49404. this.dataType = dataType;
  49405. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49406. }
  49407. /**
  49408. * @hidden Internal use
  49409. */
  49410. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49411. var dataType = undefined;
  49412. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49413. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49414. }
  49415. else if (from instanceof BABYLON.Quaternion) {
  49416. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49417. }
  49418. else if (from instanceof BABYLON.Vector3) {
  49419. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49420. }
  49421. else if (from instanceof BABYLON.Vector2) {
  49422. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49423. }
  49424. else if (from instanceof BABYLON.Color3) {
  49425. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49426. }
  49427. else if (from instanceof BABYLON.Size) {
  49428. dataType = Animation.ANIMATIONTYPE_SIZE;
  49429. }
  49430. if (dataType == undefined) {
  49431. return null;
  49432. }
  49433. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49434. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49435. animation.setKeys(keys);
  49436. if (easingFunction !== undefined) {
  49437. animation.setEasingFunction(easingFunction);
  49438. }
  49439. return animation;
  49440. };
  49441. /**
  49442. * Sets up an animation
  49443. * @param property The property to animate
  49444. * @param animationType The animation type to apply
  49445. * @param framePerSecond The frames per second of the animation
  49446. * @param easingFunction The easing function used in the animation
  49447. * @returns The created animation
  49448. */
  49449. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49450. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49451. animation.setEasingFunction(easingFunction);
  49452. return animation;
  49453. };
  49454. /**
  49455. * Create and start an animation on a node
  49456. * @param name defines the name of the global animation that will be run on all nodes
  49457. * @param node defines the root node where the animation will take place
  49458. * @param targetProperty defines property to animate
  49459. * @param framePerSecond defines the number of frame per second yo use
  49460. * @param totalFrame defines the number of frames in total
  49461. * @param from defines the initial value
  49462. * @param to defines the final value
  49463. * @param loopMode defines which loop mode you want to use (off by default)
  49464. * @param easingFunction defines the easing function to use (linear by default)
  49465. * @param onAnimationEnd defines the callback to call when animation end
  49466. * @returns the animatable created for this animation
  49467. */
  49468. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49469. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49470. if (!animation) {
  49471. return null;
  49472. }
  49473. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49474. };
  49475. /**
  49476. * Create and start an animation on a node and its descendants
  49477. * @param name defines the name of the global animation that will be run on all nodes
  49478. * @param node defines the root node where the animation will take place
  49479. * @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
  49480. * @param targetProperty defines property to animate
  49481. * @param framePerSecond defines the number of frame per second to use
  49482. * @param totalFrame defines the number of frames in total
  49483. * @param from defines the initial value
  49484. * @param to defines the final value
  49485. * @param loopMode defines which loop mode you want to use (off by default)
  49486. * @param easingFunction defines the easing function to use (linear by default)
  49487. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49488. * @returns the list of animatables created for all nodes
  49489. * @example https://www.babylonjs-playground.com/#MH0VLI
  49490. */
  49491. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49492. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49493. if (!animation) {
  49494. return null;
  49495. }
  49496. var scene = node.getScene();
  49497. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49498. };
  49499. /**
  49500. * Creates a new animation, merges it with the existing animations and starts it
  49501. * @param name Name of the animation
  49502. * @param node Node which contains the scene that begins the animations
  49503. * @param targetProperty Specifies which property to animate
  49504. * @param framePerSecond The frames per second of the animation
  49505. * @param totalFrame The total number of frames
  49506. * @param from The frame at the beginning of the animation
  49507. * @param to The frame at the end of the animation
  49508. * @param loopMode Specifies the loop mode of the animation
  49509. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49510. * @param onAnimationEnd Callback to run once the animation is complete
  49511. * @returns Nullable animation
  49512. */
  49513. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49514. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49515. if (!animation) {
  49516. return null;
  49517. }
  49518. node.animations.push(animation);
  49519. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49520. };
  49521. /**
  49522. * Transition property of an host to the target Value
  49523. * @param property The property to transition
  49524. * @param targetValue The target Value of the property
  49525. * @param host The object where the property to animate belongs
  49526. * @param scene Scene used to run the animation
  49527. * @param frameRate Framerate (in frame/s) to use
  49528. * @param transition The transition type we want to use
  49529. * @param duration The duration of the animation, in milliseconds
  49530. * @param onAnimationEnd Callback trigger at the end of the animation
  49531. * @returns Nullable animation
  49532. */
  49533. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49534. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49535. if (duration <= 0) {
  49536. host[property] = targetValue;
  49537. if (onAnimationEnd) {
  49538. onAnimationEnd();
  49539. }
  49540. return null;
  49541. }
  49542. var endFrame = frameRate * (duration / 1000);
  49543. transition.setKeys([{
  49544. frame: 0,
  49545. value: host[property].clone ? host[property].clone() : host[property]
  49546. },
  49547. {
  49548. frame: endFrame,
  49549. value: targetValue
  49550. }]);
  49551. if (!host.animations) {
  49552. host.animations = [];
  49553. }
  49554. host.animations.push(transition);
  49555. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49556. animation.onAnimationEnd = onAnimationEnd;
  49557. return animation;
  49558. };
  49559. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49560. /**
  49561. * Return the array of runtime animations currently using this animation
  49562. */
  49563. get: function () {
  49564. return this._runtimeAnimations;
  49565. },
  49566. enumerable: true,
  49567. configurable: true
  49568. });
  49569. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49570. /**
  49571. * Specifies if any of the runtime animations are currently running
  49572. */
  49573. get: function () {
  49574. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49575. var runtimeAnimation = _a[_i];
  49576. if (!runtimeAnimation.isStopped) {
  49577. return true;
  49578. }
  49579. }
  49580. return false;
  49581. },
  49582. enumerable: true,
  49583. configurable: true
  49584. });
  49585. // Methods
  49586. /**
  49587. * Converts the animation to a string
  49588. * @param fullDetails support for multiple levels of logging within scene loading
  49589. * @returns String form of the animation
  49590. */
  49591. Animation.prototype.toString = function (fullDetails) {
  49592. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49593. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49594. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49595. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49596. if (fullDetails) {
  49597. ret += ", Ranges: {";
  49598. var first = true;
  49599. for (var name in this._ranges) {
  49600. if (first) {
  49601. ret += ", ";
  49602. first = false;
  49603. }
  49604. ret += name;
  49605. }
  49606. ret += "}";
  49607. }
  49608. return ret;
  49609. };
  49610. /**
  49611. * Add an event to this animation
  49612. * @param event Event to add
  49613. */
  49614. Animation.prototype.addEvent = function (event) {
  49615. this._events.push(event);
  49616. };
  49617. /**
  49618. * Remove all events found at the given frame
  49619. * @param frame The frame to remove events from
  49620. */
  49621. Animation.prototype.removeEvents = function (frame) {
  49622. for (var index = 0; index < this._events.length; index++) {
  49623. if (this._events[index].frame === frame) {
  49624. this._events.splice(index, 1);
  49625. index--;
  49626. }
  49627. }
  49628. };
  49629. /**
  49630. * Retrieves all the events from the animation
  49631. * @returns Events from the animation
  49632. */
  49633. Animation.prototype.getEvents = function () {
  49634. return this._events;
  49635. };
  49636. /**
  49637. * Creates an animation range
  49638. * @param name Name of the animation range
  49639. * @param from Starting frame of the animation range
  49640. * @param to Ending frame of the animation
  49641. */
  49642. Animation.prototype.createRange = function (name, from, to) {
  49643. // check name not already in use; could happen for bones after serialized
  49644. if (!this._ranges[name]) {
  49645. this._ranges[name] = new AnimationRange(name, from, to);
  49646. }
  49647. };
  49648. /**
  49649. * Deletes an animation range by name
  49650. * @param name Name of the animation range to delete
  49651. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49652. */
  49653. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49654. if (deleteFrames === void 0) { deleteFrames = true; }
  49655. var range = this._ranges[name];
  49656. if (!range) {
  49657. return;
  49658. }
  49659. if (deleteFrames) {
  49660. var from = range.from;
  49661. var to = range.to;
  49662. // this loop MUST go high to low for multiple splices to work
  49663. for (var key = this._keys.length - 1; key >= 0; key--) {
  49664. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49665. this._keys.splice(key, 1);
  49666. }
  49667. }
  49668. }
  49669. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49670. };
  49671. /**
  49672. * Gets the animation range by name, or null if not defined
  49673. * @param name Name of the animation range
  49674. * @returns Nullable animation range
  49675. */
  49676. Animation.prototype.getRange = function (name) {
  49677. return this._ranges[name];
  49678. };
  49679. /**
  49680. * Gets the key frames from the animation
  49681. * @returns The key frames of the animation
  49682. */
  49683. Animation.prototype.getKeys = function () {
  49684. return this._keys;
  49685. };
  49686. /**
  49687. * Gets the highest frame rate of the animation
  49688. * @returns Highest frame rate of the animation
  49689. */
  49690. Animation.prototype.getHighestFrame = function () {
  49691. var ret = 0;
  49692. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49693. if (ret < this._keys[key].frame) {
  49694. ret = this._keys[key].frame;
  49695. }
  49696. }
  49697. return ret;
  49698. };
  49699. /**
  49700. * Gets the easing function of the animation
  49701. * @returns Easing function of the animation
  49702. */
  49703. Animation.prototype.getEasingFunction = function () {
  49704. return this._easingFunction;
  49705. };
  49706. /**
  49707. * Sets the easing function of the animation
  49708. * @param easingFunction A custom mathematical formula for animation
  49709. */
  49710. Animation.prototype.setEasingFunction = function (easingFunction) {
  49711. this._easingFunction = easingFunction;
  49712. };
  49713. /**
  49714. * Interpolates a scalar linearly
  49715. * @param startValue Start value of the animation curve
  49716. * @param endValue End value of the animation curve
  49717. * @param gradient Scalar amount to interpolate
  49718. * @returns Interpolated scalar value
  49719. */
  49720. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49721. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49722. };
  49723. /**
  49724. * Interpolates a scalar cubically
  49725. * @param startValue Start value of the animation curve
  49726. * @param outTangent End tangent of the animation
  49727. * @param endValue End value of the animation curve
  49728. * @param inTangent Start tangent of the animation curve
  49729. * @param gradient Scalar amount to interpolate
  49730. * @returns Interpolated scalar value
  49731. */
  49732. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49733. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49734. };
  49735. /**
  49736. * Interpolates a quaternion using a spherical linear interpolation
  49737. * @param startValue Start value of the animation curve
  49738. * @param endValue End value of the animation curve
  49739. * @param gradient Scalar amount to interpolate
  49740. * @returns Interpolated quaternion value
  49741. */
  49742. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49743. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49744. };
  49745. /**
  49746. * Interpolates a quaternion cubically
  49747. * @param startValue Start value of the animation curve
  49748. * @param outTangent End tangent of the animation curve
  49749. * @param endValue End value of the animation curve
  49750. * @param inTangent Start tangent of the animation curve
  49751. * @param gradient Scalar amount to interpolate
  49752. * @returns Interpolated quaternion value
  49753. */
  49754. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49755. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49756. };
  49757. /**
  49758. * Interpolates a Vector3 linearl
  49759. * @param startValue Start value of the animation curve
  49760. * @param endValue End value of the animation curve
  49761. * @param gradient Scalar amount to interpolate
  49762. * @returns Interpolated scalar value
  49763. */
  49764. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49765. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49766. };
  49767. /**
  49768. * Interpolates a Vector3 cubically
  49769. * @param startValue Start value of the animation curve
  49770. * @param outTangent End tangent of the animation
  49771. * @param endValue End value of the animation curve
  49772. * @param inTangent Start tangent of the animation curve
  49773. * @param gradient Scalar amount to interpolate
  49774. * @returns InterpolatedVector3 value
  49775. */
  49776. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49777. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49778. };
  49779. /**
  49780. * Interpolates a Vector2 linearly
  49781. * @param startValue Start value of the animation curve
  49782. * @param endValue End value of the animation curve
  49783. * @param gradient Scalar amount to interpolate
  49784. * @returns Interpolated Vector2 value
  49785. */
  49786. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49787. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49788. };
  49789. /**
  49790. * Interpolates a Vector2 cubically
  49791. * @param startValue Start value of the animation curve
  49792. * @param outTangent End tangent of the animation
  49793. * @param endValue End value of the animation curve
  49794. * @param inTangent Start tangent of the animation curve
  49795. * @param gradient Scalar amount to interpolate
  49796. * @returns Interpolated Vector2 value
  49797. */
  49798. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49799. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49800. };
  49801. /**
  49802. * Interpolates a size linearly
  49803. * @param startValue Start value of the animation curve
  49804. * @param endValue End value of the animation curve
  49805. * @param gradient Scalar amount to interpolate
  49806. * @returns Interpolated Size value
  49807. */
  49808. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49809. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49810. };
  49811. /**
  49812. * Interpolates a Color3 linearly
  49813. * @param startValue Start value of the animation curve
  49814. * @param endValue End value of the animation curve
  49815. * @param gradient Scalar amount to interpolate
  49816. * @returns Interpolated Color3 value
  49817. */
  49818. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49819. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49820. };
  49821. /**
  49822. * @hidden Internal use only
  49823. */
  49824. Animation.prototype._getKeyValue = function (value) {
  49825. if (typeof value === "function") {
  49826. return value();
  49827. }
  49828. return value;
  49829. };
  49830. /**
  49831. * @hidden Internal use only
  49832. */
  49833. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49834. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49835. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49836. }
  49837. var keys = this.getKeys();
  49838. // Try to get a hash to find the right key
  49839. 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));
  49840. if (keys[startKeyIndex].frame >= currentFrame) {
  49841. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49842. startKeyIndex--;
  49843. }
  49844. }
  49845. for (var key = startKeyIndex; key < keys.length; key++) {
  49846. var endKey = keys[key + 1];
  49847. if (endKey.frame >= currentFrame) {
  49848. var startKey = keys[key];
  49849. var startValue = this._getKeyValue(startKey.value);
  49850. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49851. return startValue;
  49852. }
  49853. var endValue = this._getKeyValue(endKey.value);
  49854. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49855. var frameDelta = endKey.frame - startKey.frame;
  49856. // gradient : percent of currentFrame between the frame inf and the frame sup
  49857. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49858. // check for easingFunction and correction of gradient
  49859. var easingFunction = this.getEasingFunction();
  49860. if (easingFunction != null) {
  49861. gradient = easingFunction.ease(gradient);
  49862. }
  49863. switch (this.dataType) {
  49864. // Float
  49865. case Animation.ANIMATIONTYPE_FLOAT:
  49866. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49867. switch (loopMode) {
  49868. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49869. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49870. return floatValue;
  49871. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49872. return offsetValue * repeatCount + floatValue;
  49873. }
  49874. break;
  49875. // Quaternion
  49876. case Animation.ANIMATIONTYPE_QUATERNION:
  49877. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49878. switch (loopMode) {
  49879. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49880. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49881. return quatValue;
  49882. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49883. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49884. }
  49885. return quatValue;
  49886. // Vector3
  49887. case Animation.ANIMATIONTYPE_VECTOR3:
  49888. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49889. switch (loopMode) {
  49890. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49891. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49892. return vec3Value;
  49893. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49894. return vec3Value.add(offsetValue.scale(repeatCount));
  49895. }
  49896. // Vector2
  49897. case Animation.ANIMATIONTYPE_VECTOR2:
  49898. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49899. switch (loopMode) {
  49900. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49901. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49902. return vec2Value;
  49903. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49904. return vec2Value.add(offsetValue.scale(repeatCount));
  49905. }
  49906. // Size
  49907. case Animation.ANIMATIONTYPE_SIZE:
  49908. switch (loopMode) {
  49909. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49910. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49911. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49912. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49913. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49914. }
  49915. // Color3
  49916. case Animation.ANIMATIONTYPE_COLOR3:
  49917. switch (loopMode) {
  49918. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49919. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49920. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49921. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49922. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49923. }
  49924. // Matrix
  49925. case Animation.ANIMATIONTYPE_MATRIX:
  49926. switch (loopMode) {
  49927. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49928. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49929. if (Animation.AllowMatricesInterpolation) {
  49930. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49931. }
  49932. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49933. return startValue;
  49934. }
  49935. default:
  49936. break;
  49937. }
  49938. break;
  49939. }
  49940. }
  49941. return this._getKeyValue(keys[keys.length - 1].value);
  49942. };
  49943. /**
  49944. * Defines the function to use to interpolate matrices
  49945. * @param startValue defines the start matrix
  49946. * @param endValue defines the end matrix
  49947. * @param gradient defines the gradient between both matrices
  49948. * @param result defines an optional target matrix where to store the interpolation
  49949. * @returns the interpolated matrix
  49950. */
  49951. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49952. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49953. if (result) {
  49954. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49955. return result;
  49956. }
  49957. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49958. }
  49959. if (result) {
  49960. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49961. return result;
  49962. }
  49963. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49964. };
  49965. /**
  49966. * Makes a copy of the animation
  49967. * @returns Cloned animation
  49968. */
  49969. Animation.prototype.clone = function () {
  49970. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49971. clone.enableBlending = this.enableBlending;
  49972. clone.blendingSpeed = this.blendingSpeed;
  49973. if (this._keys) {
  49974. clone.setKeys(this._keys);
  49975. }
  49976. if (this._ranges) {
  49977. clone._ranges = {};
  49978. for (var name in this._ranges) {
  49979. var range = this._ranges[name];
  49980. if (!range) {
  49981. continue;
  49982. }
  49983. clone._ranges[name] = range.clone();
  49984. }
  49985. }
  49986. return clone;
  49987. };
  49988. /**
  49989. * Sets the key frames of the animation
  49990. * @param values The animation key frames to set
  49991. */
  49992. Animation.prototype.setKeys = function (values) {
  49993. this._keys = values.slice(0);
  49994. };
  49995. /**
  49996. * Serializes the animation to an object
  49997. * @returns Serialized object
  49998. */
  49999. Animation.prototype.serialize = function () {
  50000. var serializationObject = {};
  50001. serializationObject.name = this.name;
  50002. serializationObject.property = this.targetProperty;
  50003. serializationObject.framePerSecond = this.framePerSecond;
  50004. serializationObject.dataType = this.dataType;
  50005. serializationObject.loopBehavior = this.loopMode;
  50006. serializationObject.enableBlending = this.enableBlending;
  50007. serializationObject.blendingSpeed = this.blendingSpeed;
  50008. var dataType = this.dataType;
  50009. serializationObject.keys = [];
  50010. var keys = this.getKeys();
  50011. for (var index = 0; index < keys.length; index++) {
  50012. var animationKey = keys[index];
  50013. var key = {};
  50014. key.frame = animationKey.frame;
  50015. switch (dataType) {
  50016. case Animation.ANIMATIONTYPE_FLOAT:
  50017. key.values = [animationKey.value];
  50018. break;
  50019. case Animation.ANIMATIONTYPE_QUATERNION:
  50020. case Animation.ANIMATIONTYPE_MATRIX:
  50021. case Animation.ANIMATIONTYPE_VECTOR3:
  50022. case Animation.ANIMATIONTYPE_COLOR3:
  50023. key.values = animationKey.value.asArray();
  50024. break;
  50025. }
  50026. serializationObject.keys.push(key);
  50027. }
  50028. serializationObject.ranges = [];
  50029. for (var name in this._ranges) {
  50030. var source = this._ranges[name];
  50031. if (!source) {
  50032. continue;
  50033. }
  50034. var range = {};
  50035. range.name = name;
  50036. range.from = source.from;
  50037. range.to = source.to;
  50038. serializationObject.ranges.push(range);
  50039. }
  50040. return serializationObject;
  50041. };
  50042. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50043. /**
  50044. * Get the float animation type
  50045. */
  50046. get: function () {
  50047. return Animation._ANIMATIONTYPE_FLOAT;
  50048. },
  50049. enumerable: true,
  50050. configurable: true
  50051. });
  50052. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50053. /**
  50054. * Get the Vector3 animation type
  50055. */
  50056. get: function () {
  50057. return Animation._ANIMATIONTYPE_VECTOR3;
  50058. },
  50059. enumerable: true,
  50060. configurable: true
  50061. });
  50062. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50063. /**
  50064. * Get the Vectpr2 animation type
  50065. */
  50066. get: function () {
  50067. return Animation._ANIMATIONTYPE_VECTOR2;
  50068. },
  50069. enumerable: true,
  50070. configurable: true
  50071. });
  50072. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50073. /**
  50074. * Get the Size animation type
  50075. */
  50076. get: function () {
  50077. return Animation._ANIMATIONTYPE_SIZE;
  50078. },
  50079. enumerable: true,
  50080. configurable: true
  50081. });
  50082. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50083. /**
  50084. * Get the Quaternion animation type
  50085. */
  50086. get: function () {
  50087. return Animation._ANIMATIONTYPE_QUATERNION;
  50088. },
  50089. enumerable: true,
  50090. configurable: true
  50091. });
  50092. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50093. /**
  50094. * Get the Matrix animation type
  50095. */
  50096. get: function () {
  50097. return Animation._ANIMATIONTYPE_MATRIX;
  50098. },
  50099. enumerable: true,
  50100. configurable: true
  50101. });
  50102. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50103. /**
  50104. * Get the Color3 animation type
  50105. */
  50106. get: function () {
  50107. return Animation._ANIMATIONTYPE_COLOR3;
  50108. },
  50109. enumerable: true,
  50110. configurable: true
  50111. });
  50112. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50113. /**
  50114. * Get the Relative Loop Mode
  50115. */
  50116. get: function () {
  50117. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50118. },
  50119. enumerable: true,
  50120. configurable: true
  50121. });
  50122. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50123. /**
  50124. * Get the Cycle Loop Mode
  50125. */
  50126. get: function () {
  50127. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50128. },
  50129. enumerable: true,
  50130. configurable: true
  50131. });
  50132. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50133. /**
  50134. * Get the Constant Loop Mode
  50135. */
  50136. get: function () {
  50137. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50138. },
  50139. enumerable: true,
  50140. configurable: true
  50141. });
  50142. /** @hidden */
  50143. Animation._UniversalLerp = function (left, right, amount) {
  50144. var constructor = left.constructor;
  50145. if (constructor.Lerp) { // Lerp supported
  50146. return constructor.Lerp(left, right, amount);
  50147. }
  50148. else if (constructor.Slerp) { // Slerp supported
  50149. return constructor.Slerp(left, right, amount);
  50150. }
  50151. else if (left.toFixed) { // Number
  50152. return left * (1.0 - amount) + amount * right;
  50153. }
  50154. else { // Blending not supported
  50155. return right;
  50156. }
  50157. };
  50158. /**
  50159. * Parses an animation object and creates an animation
  50160. * @param parsedAnimation Parsed animation object
  50161. * @returns Animation object
  50162. */
  50163. Animation.Parse = function (parsedAnimation) {
  50164. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50165. var dataType = parsedAnimation.dataType;
  50166. var keys = [];
  50167. var data;
  50168. var index;
  50169. if (parsedAnimation.enableBlending) {
  50170. animation.enableBlending = parsedAnimation.enableBlending;
  50171. }
  50172. if (parsedAnimation.blendingSpeed) {
  50173. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50174. }
  50175. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50176. var key = parsedAnimation.keys[index];
  50177. var inTangent;
  50178. var outTangent;
  50179. switch (dataType) {
  50180. case Animation.ANIMATIONTYPE_FLOAT:
  50181. data = key.values[0];
  50182. if (key.values.length >= 1) {
  50183. inTangent = key.values[1];
  50184. }
  50185. if (key.values.length >= 2) {
  50186. outTangent = key.values[2];
  50187. }
  50188. break;
  50189. case Animation.ANIMATIONTYPE_QUATERNION:
  50190. data = BABYLON.Quaternion.FromArray(key.values);
  50191. if (key.values.length >= 8) {
  50192. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50193. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50194. inTangent = _inTangent;
  50195. }
  50196. }
  50197. if (key.values.length >= 12) {
  50198. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50199. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50200. outTangent = _outTangent;
  50201. }
  50202. }
  50203. break;
  50204. case Animation.ANIMATIONTYPE_MATRIX:
  50205. data = BABYLON.Matrix.FromArray(key.values);
  50206. break;
  50207. case Animation.ANIMATIONTYPE_COLOR3:
  50208. data = BABYLON.Color3.FromArray(key.values);
  50209. break;
  50210. case Animation.ANIMATIONTYPE_VECTOR3:
  50211. default:
  50212. data = BABYLON.Vector3.FromArray(key.values);
  50213. break;
  50214. }
  50215. var keyData = {};
  50216. keyData.frame = key.frame;
  50217. keyData.value = data;
  50218. if (inTangent != undefined) {
  50219. keyData.inTangent = inTangent;
  50220. }
  50221. if (outTangent != undefined) {
  50222. keyData.outTangent = outTangent;
  50223. }
  50224. keys.push(keyData);
  50225. }
  50226. animation.setKeys(keys);
  50227. if (parsedAnimation.ranges) {
  50228. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50229. data = parsedAnimation.ranges[index];
  50230. animation.createRange(data.name, data.from, data.to);
  50231. }
  50232. }
  50233. return animation;
  50234. };
  50235. /**
  50236. * Appends the serialized animations from the source animations
  50237. * @param source Source containing the animations
  50238. * @param destination Target to store the animations
  50239. */
  50240. Animation.AppendSerializedAnimations = function (source, destination) {
  50241. if (source.animations) {
  50242. destination.animations = [];
  50243. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50244. var animation = source.animations[animationIndex];
  50245. destination.animations.push(animation.serialize());
  50246. }
  50247. }
  50248. };
  50249. /**
  50250. * Use matrix interpolation instead of using direct key value when animating matrices
  50251. */
  50252. Animation.AllowMatricesInterpolation = false;
  50253. /**
  50254. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50255. */
  50256. Animation.AllowMatrixDecomposeForInterpolation = true;
  50257. // Statics
  50258. /**
  50259. * Float animation type
  50260. */
  50261. Animation._ANIMATIONTYPE_FLOAT = 0;
  50262. /**
  50263. * Vector3 animation type
  50264. */
  50265. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50266. /**
  50267. * Quaternion animation type
  50268. */
  50269. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50270. /**
  50271. * Matrix animation type
  50272. */
  50273. Animation._ANIMATIONTYPE_MATRIX = 3;
  50274. /**
  50275. * Color3 animation type
  50276. */
  50277. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50278. /**
  50279. * Vector2 animation type
  50280. */
  50281. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50282. /**
  50283. * Size animation type
  50284. */
  50285. Animation._ANIMATIONTYPE_SIZE = 6;
  50286. /**
  50287. * Relative Loop Mode
  50288. */
  50289. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50290. /**
  50291. * Cycle Loop Mode
  50292. */
  50293. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50294. /**
  50295. * Constant Loop Mode
  50296. */
  50297. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50298. return Animation;
  50299. }());
  50300. BABYLON.Animation = Animation;
  50301. })(BABYLON || (BABYLON = {}));
  50302. //# sourceMappingURL=babylon.animation.js.map
  50303. var BABYLON;
  50304. (function (BABYLON) {
  50305. /**
  50306. * This class defines the direct association between an animation and a target
  50307. */
  50308. var TargetedAnimation = /** @class */ (function () {
  50309. function TargetedAnimation() {
  50310. }
  50311. return TargetedAnimation;
  50312. }());
  50313. BABYLON.TargetedAnimation = TargetedAnimation;
  50314. /**
  50315. * Use this class to create coordinated animations on multiple targets
  50316. */
  50317. var AnimationGroup = /** @class */ (function () {
  50318. function AnimationGroup(name, scene) {
  50319. if (scene === void 0) { scene = null; }
  50320. this.name = name;
  50321. this._targetedAnimations = new Array();
  50322. this._animatables = new Array();
  50323. this._from = Number.MAX_VALUE;
  50324. this._to = -Number.MAX_VALUE;
  50325. this._speedRatio = 1;
  50326. this.onAnimationEndObservable = new BABYLON.Observable();
  50327. /**
  50328. * This observable will notify when all animations have ended.
  50329. */
  50330. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50331. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50332. this._scene.animationGroups.push(this);
  50333. }
  50334. Object.defineProperty(AnimationGroup.prototype, "from", {
  50335. /**
  50336. * Gets the first frame
  50337. */
  50338. get: function () {
  50339. return this._from;
  50340. },
  50341. enumerable: true,
  50342. configurable: true
  50343. });
  50344. Object.defineProperty(AnimationGroup.prototype, "to", {
  50345. /**
  50346. * Gets the last frame
  50347. */
  50348. get: function () {
  50349. return this._to;
  50350. },
  50351. enumerable: true,
  50352. configurable: true
  50353. });
  50354. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50355. /**
  50356. * Define if the animations are started
  50357. */
  50358. get: function () {
  50359. return this._isStarted;
  50360. },
  50361. enumerable: true,
  50362. configurable: true
  50363. });
  50364. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50365. /**
  50366. * Gets or sets the speed ratio to use for all animations
  50367. */
  50368. get: function () {
  50369. return this._speedRatio;
  50370. },
  50371. /**
  50372. * Gets or sets the speed ratio to use for all animations
  50373. */
  50374. set: function (value) {
  50375. if (this._speedRatio === value) {
  50376. return;
  50377. }
  50378. this._speedRatio = value;
  50379. for (var index = 0; index < this._animatables.length; index++) {
  50380. var animatable = this._animatables[index];
  50381. animatable.speedRatio = this._speedRatio;
  50382. }
  50383. },
  50384. enumerable: true,
  50385. configurable: true
  50386. });
  50387. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50388. /**
  50389. * Gets the targeted animations for this animation group
  50390. */
  50391. get: function () {
  50392. return this._targetedAnimations;
  50393. },
  50394. enumerable: true,
  50395. configurable: true
  50396. });
  50397. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50398. /**
  50399. * returning the list of animatables controlled by this animation group.
  50400. */
  50401. get: function () {
  50402. return this._animatables;
  50403. },
  50404. enumerable: true,
  50405. configurable: true
  50406. });
  50407. /**
  50408. * Add an animation (with its target) in the group
  50409. * @param animation defines the animation we want to add
  50410. * @param target defines the target of the animation
  50411. * @returns the {BABYLON.TargetedAnimation} object
  50412. */
  50413. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50414. var targetedAnimation = {
  50415. animation: animation,
  50416. target: target
  50417. };
  50418. var keys = animation.getKeys();
  50419. if (this._from > keys[0].frame) {
  50420. this._from = keys[0].frame;
  50421. }
  50422. if (this._to < keys[keys.length - 1].frame) {
  50423. this._to = keys[keys.length - 1].frame;
  50424. }
  50425. this._targetedAnimations.push(targetedAnimation);
  50426. return targetedAnimation;
  50427. };
  50428. /**
  50429. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50430. * It can add constant keys at begin or end
  50431. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50432. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50433. */
  50434. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50435. if (beginFrame === void 0) { beginFrame = null; }
  50436. if (endFrame === void 0) { endFrame = null; }
  50437. if (beginFrame == null)
  50438. beginFrame = this._from;
  50439. if (endFrame == null)
  50440. endFrame = this._to;
  50441. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50442. var targetedAnimation = this._targetedAnimations[index];
  50443. var keys = targetedAnimation.animation.getKeys();
  50444. var startKey = keys[0];
  50445. var endKey = keys[keys.length - 1];
  50446. if (startKey.frame > beginFrame) {
  50447. var newKey = {
  50448. frame: beginFrame,
  50449. value: startKey.value,
  50450. inTangent: startKey.inTangent,
  50451. outTangent: startKey.outTangent,
  50452. interpolation: startKey.interpolation
  50453. };
  50454. keys.splice(0, 0, newKey);
  50455. }
  50456. if (endKey.frame < endFrame) {
  50457. var newKey = {
  50458. frame: endFrame,
  50459. value: endKey.value,
  50460. inTangent: endKey.outTangent,
  50461. outTangent: endKey.outTangent,
  50462. interpolation: endKey.interpolation
  50463. };
  50464. keys.push(newKey);
  50465. }
  50466. }
  50467. this._from = beginFrame;
  50468. this._to = endFrame;
  50469. return this;
  50470. };
  50471. /**
  50472. * Start all animations on given targets
  50473. * @param loop defines if animations must loop
  50474. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50475. * @param from defines the from key (optional)
  50476. * @param to defines the to key (optional)
  50477. * @returns the current animation group
  50478. */
  50479. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50480. var _this = this;
  50481. if (loop === void 0) { loop = false; }
  50482. if (speedRatio === void 0) { speedRatio = 1; }
  50483. if (this._isStarted || this._targetedAnimations.length === 0) {
  50484. return this;
  50485. }
  50486. var _loop_1 = function (targetedAnimation) {
  50487. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50488. animatable.onAnimationEnd = function () {
  50489. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50490. _this._checkAnimationGroupEnded(animatable);
  50491. };
  50492. this_1._animatables.push(animatable);
  50493. };
  50494. var this_1 = this;
  50495. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50496. var targetedAnimation = _a[_i];
  50497. _loop_1(targetedAnimation);
  50498. }
  50499. this._speedRatio = speedRatio;
  50500. this._isStarted = true;
  50501. return this;
  50502. };
  50503. /**
  50504. * Pause all animations
  50505. */
  50506. AnimationGroup.prototype.pause = function () {
  50507. if (!this._isStarted) {
  50508. return this;
  50509. }
  50510. for (var index = 0; index < this._animatables.length; index++) {
  50511. var animatable = this._animatables[index];
  50512. animatable.pause();
  50513. }
  50514. return this;
  50515. };
  50516. /**
  50517. * Play all animations to initial state
  50518. * This function will start() the animations if they were not started or will restart() them if they were paused
  50519. * @param loop defines if animations must loop
  50520. */
  50521. AnimationGroup.prototype.play = function (loop) {
  50522. // only if all animatables are ready and exist
  50523. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50524. if (loop !== undefined) {
  50525. for (var index = 0; index < this._animatables.length; index++) {
  50526. var animatable = this._animatables[index];
  50527. animatable.loopAnimation = loop;
  50528. }
  50529. }
  50530. this.restart();
  50531. }
  50532. else {
  50533. this.stop();
  50534. this.start(loop, this._speedRatio);
  50535. }
  50536. return this;
  50537. };
  50538. /**
  50539. * Reset all animations to initial state
  50540. */
  50541. AnimationGroup.prototype.reset = function () {
  50542. if (!this._isStarted) {
  50543. return this;
  50544. }
  50545. for (var index = 0; index < this._animatables.length; index++) {
  50546. var animatable = this._animatables[index];
  50547. animatable.reset();
  50548. }
  50549. return this;
  50550. };
  50551. /**
  50552. * Restart animations from key 0
  50553. */
  50554. AnimationGroup.prototype.restart = function () {
  50555. if (!this._isStarted) {
  50556. return this;
  50557. }
  50558. for (var index = 0; index < this._animatables.length; index++) {
  50559. var animatable = this._animatables[index];
  50560. animatable.restart();
  50561. }
  50562. return this;
  50563. };
  50564. /**
  50565. * Stop all animations
  50566. */
  50567. AnimationGroup.prototype.stop = function () {
  50568. if (!this._isStarted) {
  50569. return this;
  50570. }
  50571. var list = this._animatables.slice();
  50572. for (var index = 0; index < list.length; index++) {
  50573. list[index].stop();
  50574. }
  50575. this._isStarted = false;
  50576. return this;
  50577. };
  50578. /**
  50579. * Set animation weight for all animatables
  50580. * @param weight defines the weight to use
  50581. * @return the animationGroup
  50582. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50583. */
  50584. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50585. for (var index = 0; index < this._animatables.length; index++) {
  50586. var animatable = this._animatables[index];
  50587. animatable.weight = weight;
  50588. }
  50589. return this;
  50590. };
  50591. /**
  50592. * Synchronize and normalize all animatables with a source animatable
  50593. * @param root defines the root animatable to synchronize with
  50594. * @return the animationGroup
  50595. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50596. */
  50597. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50598. for (var index = 0; index < this._animatables.length; index++) {
  50599. var animatable = this._animatables[index];
  50600. animatable.syncWith(root);
  50601. }
  50602. return this;
  50603. };
  50604. /**
  50605. * Goes to a specific frame in this animation group
  50606. * @param frame the frame number to go to
  50607. * @return the animationGroup
  50608. */
  50609. AnimationGroup.prototype.goToFrame = function (frame) {
  50610. if (!this._isStarted) {
  50611. return this;
  50612. }
  50613. for (var index = 0; index < this._animatables.length; index++) {
  50614. var animatable = this._animatables[index];
  50615. animatable.goToFrame(frame);
  50616. }
  50617. return this;
  50618. };
  50619. /**
  50620. * Dispose all associated resources
  50621. */
  50622. AnimationGroup.prototype.dispose = function () {
  50623. this._targetedAnimations = [];
  50624. this._animatables = [];
  50625. var index = this._scene.animationGroups.indexOf(this);
  50626. if (index > -1) {
  50627. this._scene.animationGroups.splice(index, 1);
  50628. }
  50629. };
  50630. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50631. // animatable should be taken out of the array
  50632. var idx = this._animatables.indexOf(animatable);
  50633. if (idx > -1) {
  50634. this._animatables.splice(idx, 1);
  50635. }
  50636. // all animatables were removed? animation group ended!
  50637. if (this._animatables.length === 0) {
  50638. this._isStarted = false;
  50639. this.onAnimationGroupEndObservable.notifyObservers(this);
  50640. }
  50641. };
  50642. return AnimationGroup;
  50643. }());
  50644. BABYLON.AnimationGroup = AnimationGroup;
  50645. })(BABYLON || (BABYLON = {}));
  50646. //# sourceMappingURL=babylon.animationGroup.js.map
  50647. var BABYLON;
  50648. (function (BABYLON) {
  50649. /**
  50650. * Defines a runtime animation
  50651. */
  50652. var RuntimeAnimation = /** @class */ (function () {
  50653. /**
  50654. * Create a new RuntimeAnimation object
  50655. * @param target defines the target of the animation
  50656. * @param animation defines the source animation object
  50657. * @param scene defines the hosting scene
  50658. * @param host defines the initiating Animatable
  50659. */
  50660. function RuntimeAnimation(target, animation, scene, host) {
  50661. var _this = this;
  50662. this._events = new Array();
  50663. /**
  50664. * The current frame of the runtime animation
  50665. */
  50666. this._currentFrame = 0;
  50667. /**
  50668. * The original value of the runtime animation
  50669. */
  50670. this._originalValue = new Array();
  50671. /**
  50672. * The offsets cache of the runtime animation
  50673. */
  50674. this._offsetsCache = {};
  50675. /**
  50676. * The high limits cache of the runtime animation
  50677. */
  50678. this._highLimitsCache = {};
  50679. /**
  50680. * Specifies if the runtime animation has been stopped
  50681. */
  50682. this._stopped = false;
  50683. /**
  50684. * The blending factor of the runtime animation
  50685. */
  50686. this._blendingFactor = 0;
  50687. /**
  50688. * The target path of the runtime animation
  50689. */
  50690. this._targetPath = "";
  50691. /**
  50692. * The weight of the runtime animation
  50693. */
  50694. this._weight = 1.0;
  50695. /**
  50696. * The ratio offset of the runtime animation
  50697. */
  50698. this._ratioOffset = 0;
  50699. /**
  50700. * The previous delay of the runtime animation
  50701. */
  50702. this._previousDelay = 0;
  50703. /**
  50704. * The previous ratio of the runtime animation
  50705. */
  50706. this._previousRatio = 0;
  50707. this._animation = animation;
  50708. this._target = target;
  50709. this._scene = scene;
  50710. this._host = host;
  50711. animation._runtimeAnimations.push(this);
  50712. // Cloning events locally
  50713. var events = animation.getEvents();
  50714. if (events && events.length > 0) {
  50715. events.forEach(function (e) {
  50716. _this._events.push(e._clone());
  50717. });
  50718. }
  50719. }
  50720. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50721. /**
  50722. * Gets the current frame of the runtime animation
  50723. */
  50724. get: function () {
  50725. return this._currentFrame;
  50726. },
  50727. enumerable: true,
  50728. configurable: true
  50729. });
  50730. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50731. /**
  50732. * Gets the weight of the runtime animation
  50733. */
  50734. get: function () {
  50735. return this._weight;
  50736. },
  50737. enumerable: true,
  50738. configurable: true
  50739. });
  50740. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50741. /**
  50742. * Gets the current value of the runtime animation
  50743. */
  50744. get: function () {
  50745. return this._currentValue;
  50746. },
  50747. enumerable: true,
  50748. configurable: true
  50749. });
  50750. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50751. /**
  50752. * Gets the target path of the runtime animation
  50753. */
  50754. get: function () {
  50755. return this._targetPath;
  50756. },
  50757. enumerable: true,
  50758. configurable: true
  50759. });
  50760. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50761. /**
  50762. * Gets the actual target of the runtime animation
  50763. */
  50764. get: function () {
  50765. return this._activeTarget;
  50766. },
  50767. enumerable: true,
  50768. configurable: true
  50769. });
  50770. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50771. /**
  50772. * Gets the animation from the runtime animation
  50773. */
  50774. get: function () {
  50775. return this._animation;
  50776. },
  50777. enumerable: true,
  50778. configurable: true
  50779. });
  50780. /**
  50781. * Resets the runtime animation to the beginning
  50782. * @param restoreOriginal defines whether to restore the target property to the original value
  50783. */
  50784. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50785. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50786. if (restoreOriginal) {
  50787. if (this._target instanceof Array) {
  50788. var index = 0;
  50789. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50790. var target = _a[_i];
  50791. if (this._originalValue[index] !== undefined) {
  50792. this._setValue(target, this._originalValue[index], -1);
  50793. }
  50794. index++;
  50795. }
  50796. }
  50797. else {
  50798. if (this._originalValue[0] !== undefined) {
  50799. this._setValue(this._target, this._originalValue[0], -1);
  50800. }
  50801. }
  50802. }
  50803. this._offsetsCache = {};
  50804. this._highLimitsCache = {};
  50805. this._currentFrame = 0;
  50806. this._blendingFactor = 0;
  50807. this._originalValue = new Array();
  50808. // Events
  50809. for (var index = 0; index < this._events.length; index++) {
  50810. this._events[index].isDone = false;
  50811. }
  50812. };
  50813. /**
  50814. * Specifies if the runtime animation is stopped
  50815. * @returns Boolean specifying if the runtime animation is stopped
  50816. */
  50817. RuntimeAnimation.prototype.isStopped = function () {
  50818. return this._stopped;
  50819. };
  50820. /**
  50821. * Disposes of the runtime animation
  50822. */
  50823. RuntimeAnimation.prototype.dispose = function () {
  50824. var index = this._animation.runtimeAnimations.indexOf(this);
  50825. if (index > -1) {
  50826. this._animation.runtimeAnimations.splice(index, 1);
  50827. }
  50828. };
  50829. /**
  50830. * Interpolates the animation from the current frame
  50831. * @param currentFrame The frame to interpolate the animation to
  50832. * @param repeatCount The number of times that the animation should loop
  50833. * @param loopMode The type of looping mode to use
  50834. * @param offsetValue Animation offset value
  50835. * @param highLimitValue The high limit value
  50836. * @returns The interpolated value
  50837. */
  50838. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50839. this._currentFrame = currentFrame;
  50840. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50841. this._workValue = BABYLON.Matrix.Zero();
  50842. }
  50843. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50844. };
  50845. /**
  50846. * Apply the interpolated value to the target
  50847. * @param currentValue defines the value computed by the animation
  50848. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50849. */
  50850. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50851. if (weight === void 0) { weight = 1.0; }
  50852. if (this._target instanceof Array) {
  50853. var index = 0;
  50854. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50855. var target = _a[_i];
  50856. this._setValue(target, currentValue, weight, index);
  50857. index++;
  50858. }
  50859. }
  50860. else {
  50861. this._setValue(this._target, currentValue, weight);
  50862. }
  50863. };
  50864. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50865. if (targetIndex === void 0) { targetIndex = 0; }
  50866. // Set value
  50867. var path;
  50868. var destination;
  50869. var targetPropertyPath = this._animation.targetPropertyPath;
  50870. if (targetPropertyPath.length > 1) {
  50871. var property = target[targetPropertyPath[0]];
  50872. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50873. property = property[targetPropertyPath[index]];
  50874. }
  50875. path = targetPropertyPath[targetPropertyPath.length - 1];
  50876. destination = property;
  50877. }
  50878. else {
  50879. path = targetPropertyPath[0];
  50880. destination = target;
  50881. }
  50882. this._targetPath = path;
  50883. this._activeTarget = destination;
  50884. this._weight = weight;
  50885. if (this._originalValue[targetIndex] === undefined) {
  50886. var originalValue = void 0;
  50887. if (destination.getRestPose && path === "_matrix") { // For bones
  50888. originalValue = destination.getRestPose();
  50889. }
  50890. else {
  50891. originalValue = destination[path];
  50892. }
  50893. if (originalValue && originalValue.clone) {
  50894. this._originalValue[targetIndex] = originalValue.clone();
  50895. }
  50896. else {
  50897. this._originalValue[targetIndex] = originalValue;
  50898. }
  50899. }
  50900. // Blending
  50901. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50902. if (enableBlending && this._blendingFactor <= 1.0) {
  50903. if (!this._originalBlendValue) {
  50904. var originalValue = destination[path];
  50905. if (originalValue.clone) {
  50906. this._originalBlendValue = originalValue.clone();
  50907. }
  50908. else {
  50909. this._originalBlendValue = originalValue;
  50910. }
  50911. }
  50912. if (this._originalBlendValue.m) { // Matrix
  50913. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50914. if (this._currentValue) {
  50915. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50916. }
  50917. else {
  50918. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50919. }
  50920. }
  50921. else {
  50922. if (this._currentValue) {
  50923. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50924. }
  50925. else {
  50926. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50927. }
  50928. }
  50929. }
  50930. else {
  50931. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50932. }
  50933. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50934. this._blendingFactor += blendingSpeed;
  50935. }
  50936. else {
  50937. this._currentValue = currentValue;
  50938. }
  50939. if (weight !== -1.0) {
  50940. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50941. }
  50942. else {
  50943. destination[path] = this._currentValue;
  50944. }
  50945. if (target.markAsDirty) {
  50946. target.markAsDirty(this._animation.targetProperty);
  50947. }
  50948. };
  50949. /**
  50950. * Gets the loop pmode of the runtime animation
  50951. * @returns Loop Mode
  50952. */
  50953. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50954. if (this._target && this._target.animationPropertiesOverride) {
  50955. return this._target.animationPropertiesOverride.loopMode;
  50956. }
  50957. return this._animation.loopMode;
  50958. };
  50959. /**
  50960. * Move the current animation to a given frame
  50961. * @param frame defines the frame to move to
  50962. */
  50963. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50964. var keys = this._animation.getKeys();
  50965. if (frame < keys[0].frame) {
  50966. frame = keys[0].frame;
  50967. }
  50968. else if (frame > keys[keys.length - 1].frame) {
  50969. frame = keys[keys.length - 1].frame;
  50970. }
  50971. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50972. this.setValue(currentValue, -1);
  50973. };
  50974. /**
  50975. * @hidden Internal use only
  50976. */
  50977. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50978. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50979. this._ratioOffset = this._previousRatio - newRatio;
  50980. };
  50981. /**
  50982. * Execute the current animation
  50983. * @param delay defines the delay to add to the current frame
  50984. * @param from defines the lower bound of the animation range
  50985. * @param to defines the upper bound of the animation range
  50986. * @param loop defines if the current animation must loop
  50987. * @param speedRatio defines the current speed ratio
  50988. * @param weight defines the weight of the animation (default is -1 so no weight)
  50989. * @returns a boolean indicating if the animation is running
  50990. */
  50991. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50992. if (weight === void 0) { weight = -1.0; }
  50993. var targetPropertyPath = this._animation.targetPropertyPath;
  50994. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50995. this._stopped = true;
  50996. return false;
  50997. }
  50998. var returnValue = true;
  50999. var keys = this._animation.getKeys();
  51000. // Adding a start key at frame 0 if missing
  51001. if (keys[0].frame !== 0) {
  51002. var newKey = { frame: 0, value: keys[0].value };
  51003. keys.splice(0, 0, newKey);
  51004. }
  51005. // Adding a duplicate key when there is only one key at frame zero
  51006. else if (keys.length === 1) {
  51007. var newKey = { frame: 0.001, value: keys[0].value };
  51008. keys.push(newKey);
  51009. }
  51010. // Check limits
  51011. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51012. from = keys[0].frame;
  51013. }
  51014. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51015. to = keys[keys.length - 1].frame;
  51016. }
  51017. //to and from cannot be the same key
  51018. if (from === to) {
  51019. if (from > keys[0].frame) {
  51020. from--;
  51021. }
  51022. else if (to < keys[keys.length - 1].frame) {
  51023. to++;
  51024. }
  51025. }
  51026. // Compute ratio
  51027. var range = to - from;
  51028. var offsetValue;
  51029. // ratio represents the frame delta between from and to
  51030. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51031. var highLimitValue = 0;
  51032. this._previousDelay = delay;
  51033. this._previousRatio = ratio;
  51034. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51035. returnValue = false;
  51036. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51037. }
  51038. else {
  51039. // Get max value if required
  51040. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51041. var keyOffset = to.toString() + from.toString();
  51042. if (!this._offsetsCache[keyOffset]) {
  51043. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51044. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51045. switch (this._animation.dataType) {
  51046. // Float
  51047. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51048. this._offsetsCache[keyOffset] = toValue - fromValue;
  51049. break;
  51050. // Quaternion
  51051. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51052. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51053. break;
  51054. // Vector3
  51055. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51056. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51057. // Vector2
  51058. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51059. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51060. // Size
  51061. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51062. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51063. // Color3
  51064. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51065. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51066. default:
  51067. break;
  51068. }
  51069. this._highLimitsCache[keyOffset] = toValue;
  51070. }
  51071. highLimitValue = this._highLimitsCache[keyOffset];
  51072. offsetValue = this._offsetsCache[keyOffset];
  51073. }
  51074. }
  51075. if (offsetValue === undefined) {
  51076. switch (this._animation.dataType) {
  51077. // Float
  51078. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51079. offsetValue = 0;
  51080. break;
  51081. // Quaternion
  51082. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51083. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51084. break;
  51085. // Vector3
  51086. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51087. offsetValue = BABYLON.Vector3.Zero();
  51088. break;
  51089. // Vector2
  51090. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51091. offsetValue = BABYLON.Vector2.Zero();
  51092. break;
  51093. // Size
  51094. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51095. offsetValue = BABYLON.Size.Zero();
  51096. break;
  51097. // Color3
  51098. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51099. offsetValue = BABYLON.Color3.Black();
  51100. }
  51101. }
  51102. // Compute value
  51103. var repeatCount = (ratio / range) >> 0;
  51104. var currentFrame = returnValue ? from + ratio % range : to;
  51105. // Need to normalize?
  51106. if (this._host && this._host.syncRoot) {
  51107. var syncRoot = this._host.syncRoot;
  51108. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51109. currentFrame = from + (to - from) * hostNormalizedFrame;
  51110. }
  51111. // Reset events if looping
  51112. var events = this._events;
  51113. if (range > 0 && this.currentFrame > currentFrame ||
  51114. range < 0 && this.currentFrame < currentFrame) {
  51115. // Need to reset animation events
  51116. for (var index = 0; index < events.length; index++) {
  51117. if (!events[index].onlyOnce) {
  51118. // reset event, the animation is looping
  51119. events[index].isDone = false;
  51120. }
  51121. }
  51122. }
  51123. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51124. // Set value
  51125. this.setValue(currentValue, weight);
  51126. // Check events
  51127. for (var index = 0; index < events.length; index++) {
  51128. // Make sure current frame has passed event frame and that event frame is within the current range
  51129. // Also, handle both forward and reverse animations
  51130. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51131. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51132. var event = events[index];
  51133. if (!event.isDone) {
  51134. // If event should be done only once, remove it.
  51135. if (event.onlyOnce) {
  51136. events.splice(index, 1);
  51137. index--;
  51138. }
  51139. event.isDone = true;
  51140. event.action();
  51141. } // Don't do anything if the event has already be done.
  51142. }
  51143. }
  51144. if (!returnValue) {
  51145. this._stopped = true;
  51146. }
  51147. return returnValue;
  51148. };
  51149. return RuntimeAnimation;
  51150. }());
  51151. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51152. })(BABYLON || (BABYLON = {}));
  51153. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51154. var BABYLON;
  51155. (function (BABYLON) {
  51156. /**
  51157. * Class used to store an actual running animation
  51158. */
  51159. var Animatable = /** @class */ (function () {
  51160. /**
  51161. * Creates a new Animatable
  51162. * @param scene defines the hosting scene
  51163. * @param target defines the target object
  51164. * @param fromFrame defines the starting frame number (default is 0)
  51165. * @param toFrame defines the ending frame number (default is 100)
  51166. * @param loopAnimation defines if the animation must loop (default is false)
  51167. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51168. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51169. * @param animations defines a group of animation to add to the new Animatable
  51170. */
  51171. function Animatable(scene,
  51172. /** defines the target object */
  51173. target,
  51174. /** defines the starting frame number (default is 0) */
  51175. fromFrame,
  51176. /** defines the ending frame number (default is 100) */
  51177. toFrame,
  51178. /** defines if the animation must loop (default is false) */
  51179. loopAnimation, speedRatio,
  51180. /** defines a callback to call when animation ends if it is not looping */
  51181. onAnimationEnd, animations) {
  51182. if (fromFrame === void 0) { fromFrame = 0; }
  51183. if (toFrame === void 0) { toFrame = 100; }
  51184. if (loopAnimation === void 0) { loopAnimation = false; }
  51185. if (speedRatio === void 0) { speedRatio = 1.0; }
  51186. this.target = target;
  51187. this.fromFrame = fromFrame;
  51188. this.toFrame = toFrame;
  51189. this.loopAnimation = loopAnimation;
  51190. this.onAnimationEnd = onAnimationEnd;
  51191. this._localDelayOffset = null;
  51192. this._pausedDelay = null;
  51193. this._runtimeAnimations = new Array();
  51194. this._paused = false;
  51195. this._speedRatio = 1;
  51196. this._weight = -1.0;
  51197. /**
  51198. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51199. * This will only apply for non looping animation (default is true)
  51200. */
  51201. this.disposeOnEnd = true;
  51202. /**
  51203. * Gets a boolean indicating if the animation has started
  51204. */
  51205. this.animationStarted = false;
  51206. /**
  51207. * Observer raised when the animation ends
  51208. */
  51209. this.onAnimationEndObservable = new BABYLON.Observable();
  51210. this._scene = scene;
  51211. if (animations) {
  51212. this.appendAnimations(target, animations);
  51213. }
  51214. this._speedRatio = speedRatio;
  51215. scene._activeAnimatables.push(this);
  51216. }
  51217. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51218. /**
  51219. * Gets the root Animatable used to synchronize and normalize animations
  51220. */
  51221. get: function () {
  51222. return this._syncRoot;
  51223. },
  51224. enumerable: true,
  51225. configurable: true
  51226. });
  51227. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51228. /**
  51229. * Gets the current frame of the first RuntimeAnimation
  51230. * Used to synchronize Animatables
  51231. */
  51232. get: function () {
  51233. if (this._runtimeAnimations.length === 0) {
  51234. return 0;
  51235. }
  51236. return this._runtimeAnimations[0].currentFrame;
  51237. },
  51238. enumerable: true,
  51239. configurable: true
  51240. });
  51241. Object.defineProperty(Animatable.prototype, "weight", {
  51242. /**
  51243. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51244. */
  51245. get: function () {
  51246. return this._weight;
  51247. },
  51248. set: function (value) {
  51249. if (value === -1) { // -1 is ok and means no weight
  51250. this._weight = -1;
  51251. return;
  51252. }
  51253. // Else weight must be in [0, 1] range
  51254. this._weight = Math.min(Math.max(value, 0), 1.0);
  51255. },
  51256. enumerable: true,
  51257. configurable: true
  51258. });
  51259. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51260. /**
  51261. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51262. */
  51263. get: function () {
  51264. return this._speedRatio;
  51265. },
  51266. set: function (value) {
  51267. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51268. var animation = this._runtimeAnimations[index];
  51269. animation._prepareForSpeedRatioChange(value);
  51270. }
  51271. this._speedRatio = value;
  51272. },
  51273. enumerable: true,
  51274. configurable: true
  51275. });
  51276. // Methods
  51277. /**
  51278. * Synchronize and normalize current Animatable with a source Animatable
  51279. * This is useful when using animation weights and when animations are not of the same length
  51280. * @param root defines the root Animatable to synchronize with
  51281. * @returns the current Animatable
  51282. */
  51283. Animatable.prototype.syncWith = function (root) {
  51284. this._syncRoot = root;
  51285. if (root) {
  51286. // Make sure this animatable will animate after the root
  51287. var index = this._scene._activeAnimatables.indexOf(this);
  51288. if (index > -1) {
  51289. this._scene._activeAnimatables.splice(index, 1);
  51290. this._scene._activeAnimatables.push(this);
  51291. }
  51292. }
  51293. return this;
  51294. };
  51295. /**
  51296. * Gets the list of runtime animations
  51297. * @returns an array of RuntimeAnimation
  51298. */
  51299. Animatable.prototype.getAnimations = function () {
  51300. return this._runtimeAnimations;
  51301. };
  51302. /**
  51303. * Adds more animations to the current animatable
  51304. * @param target defines the target of the animations
  51305. * @param animations defines the new animations to add
  51306. */
  51307. Animatable.prototype.appendAnimations = function (target, animations) {
  51308. for (var index = 0; index < animations.length; index++) {
  51309. var animation = animations[index];
  51310. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51311. }
  51312. };
  51313. /**
  51314. * Gets the source animation for a specific property
  51315. * @param property defines the propertyu to look for
  51316. * @returns null or the source animation for the given property
  51317. */
  51318. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51319. var runtimeAnimations = this._runtimeAnimations;
  51320. for (var index = 0; index < runtimeAnimations.length; index++) {
  51321. if (runtimeAnimations[index].animation.targetProperty === property) {
  51322. return runtimeAnimations[index].animation;
  51323. }
  51324. }
  51325. return null;
  51326. };
  51327. /**
  51328. * Gets the runtime animation for a specific property
  51329. * @param property defines the propertyu to look for
  51330. * @returns null or the runtime animation for the given property
  51331. */
  51332. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51333. var runtimeAnimations = this._runtimeAnimations;
  51334. for (var index = 0; index < runtimeAnimations.length; index++) {
  51335. if (runtimeAnimations[index].animation.targetProperty === property) {
  51336. return runtimeAnimations[index];
  51337. }
  51338. }
  51339. return null;
  51340. };
  51341. /**
  51342. * Resets the animatable to its original state
  51343. */
  51344. Animatable.prototype.reset = function () {
  51345. var runtimeAnimations = this._runtimeAnimations;
  51346. for (var index = 0; index < runtimeAnimations.length; index++) {
  51347. runtimeAnimations[index].reset(true);
  51348. }
  51349. this._localDelayOffset = null;
  51350. this._pausedDelay = null;
  51351. };
  51352. /**
  51353. * Allows the animatable to blend with current running animations
  51354. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51355. * @param blendingSpeed defines the blending speed to use
  51356. */
  51357. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51358. var runtimeAnimations = this._runtimeAnimations;
  51359. for (var index = 0; index < runtimeAnimations.length; index++) {
  51360. runtimeAnimations[index].animation.enableBlending = true;
  51361. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51362. }
  51363. };
  51364. /**
  51365. * Disable animation blending
  51366. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51367. */
  51368. Animatable.prototype.disableBlending = function () {
  51369. var runtimeAnimations = this._runtimeAnimations;
  51370. for (var index = 0; index < runtimeAnimations.length; index++) {
  51371. runtimeAnimations[index].animation.enableBlending = false;
  51372. }
  51373. };
  51374. /**
  51375. * Jump directly to a given frame
  51376. * @param frame defines the frame to jump to
  51377. */
  51378. Animatable.prototype.goToFrame = function (frame) {
  51379. var runtimeAnimations = this._runtimeAnimations;
  51380. if (runtimeAnimations[0]) {
  51381. var fps = runtimeAnimations[0].animation.framePerSecond;
  51382. var currentFrame = runtimeAnimations[0].currentFrame;
  51383. var adjustTime = frame - currentFrame;
  51384. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51385. if (this._localDelayOffset === null) {
  51386. this._localDelayOffset = 0;
  51387. }
  51388. this._localDelayOffset -= delay;
  51389. }
  51390. for (var index = 0; index < runtimeAnimations.length; index++) {
  51391. runtimeAnimations[index].goToFrame(frame);
  51392. }
  51393. };
  51394. /**
  51395. * Pause the animation
  51396. */
  51397. Animatable.prototype.pause = function () {
  51398. if (this._paused) {
  51399. return;
  51400. }
  51401. this._paused = true;
  51402. };
  51403. /**
  51404. * Restart the animation
  51405. */
  51406. Animatable.prototype.restart = function () {
  51407. this._paused = false;
  51408. };
  51409. Animatable.prototype._raiseOnAnimationEnd = function () {
  51410. if (this.onAnimationEnd) {
  51411. this.onAnimationEnd();
  51412. }
  51413. this.onAnimationEndObservable.notifyObservers(this);
  51414. };
  51415. /**
  51416. * Stop and delete the current animation
  51417. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51418. * @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)
  51419. */
  51420. Animatable.prototype.stop = function (animationName, targetMask) {
  51421. if (animationName || targetMask) {
  51422. var idx = this._scene._activeAnimatables.indexOf(this);
  51423. if (idx > -1) {
  51424. var runtimeAnimations = this._runtimeAnimations;
  51425. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51426. var runtimeAnimation = runtimeAnimations[index];
  51427. if (animationName && runtimeAnimation.animation.name != animationName) {
  51428. continue;
  51429. }
  51430. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51431. continue;
  51432. }
  51433. runtimeAnimation.dispose();
  51434. runtimeAnimations.splice(index, 1);
  51435. }
  51436. if (runtimeAnimations.length == 0) {
  51437. this._scene._activeAnimatables.splice(idx, 1);
  51438. this._raiseOnAnimationEnd();
  51439. }
  51440. }
  51441. }
  51442. else {
  51443. var index = this._scene._activeAnimatables.indexOf(this);
  51444. if (index > -1) {
  51445. this._scene._activeAnimatables.splice(index, 1);
  51446. var runtimeAnimations = this._runtimeAnimations;
  51447. for (var index = 0; index < runtimeAnimations.length; index++) {
  51448. runtimeAnimations[index].dispose();
  51449. }
  51450. this._raiseOnAnimationEnd();
  51451. }
  51452. }
  51453. };
  51454. /**
  51455. * Wait asynchronously for the animation to end
  51456. * @returns a promise which will be fullfilled when the animation ends
  51457. */
  51458. Animatable.prototype.waitAsync = function () {
  51459. var _this = this;
  51460. return new Promise(function (resolve, reject) {
  51461. _this.onAnimationEndObservable.add(function () {
  51462. resolve(_this);
  51463. }, undefined, undefined, _this, true);
  51464. });
  51465. };
  51466. /** @hidden */
  51467. Animatable.prototype._animate = function (delay) {
  51468. if (this._paused) {
  51469. this.animationStarted = false;
  51470. if (this._pausedDelay === null) {
  51471. this._pausedDelay = delay;
  51472. }
  51473. return true;
  51474. }
  51475. if (this._localDelayOffset === null) {
  51476. this._localDelayOffset = delay;
  51477. this._pausedDelay = null;
  51478. }
  51479. else if (this._pausedDelay !== null) {
  51480. this._localDelayOffset += delay - this._pausedDelay;
  51481. this._pausedDelay = null;
  51482. }
  51483. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51484. return true;
  51485. }
  51486. // Animating
  51487. var running = false;
  51488. var runtimeAnimations = this._runtimeAnimations;
  51489. var index;
  51490. for (index = 0; index < runtimeAnimations.length; index++) {
  51491. var animation = runtimeAnimations[index];
  51492. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51493. running = running || isRunning;
  51494. }
  51495. this.animationStarted = running;
  51496. if (!running) {
  51497. if (this.disposeOnEnd) {
  51498. // Remove from active animatables
  51499. index = this._scene._activeAnimatables.indexOf(this);
  51500. this._scene._activeAnimatables.splice(index, 1);
  51501. // Dispose all runtime animations
  51502. for (index = 0; index < runtimeAnimations.length; index++) {
  51503. runtimeAnimations[index].dispose();
  51504. }
  51505. }
  51506. this._raiseOnAnimationEnd();
  51507. if (this.disposeOnEnd) {
  51508. this.onAnimationEnd = null;
  51509. this.onAnimationEndObservable.clear();
  51510. }
  51511. }
  51512. return running;
  51513. };
  51514. return Animatable;
  51515. }());
  51516. BABYLON.Animatable = Animatable;
  51517. })(BABYLON || (BABYLON = {}));
  51518. //# sourceMappingURL=babylon.animatable.js.map
  51519. var BABYLON;
  51520. (function (BABYLON) {
  51521. var EasingFunction = /** @class */ (function () {
  51522. function EasingFunction() {
  51523. // Properties
  51524. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51525. }
  51526. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51527. get: function () {
  51528. return EasingFunction._EASINGMODE_EASEIN;
  51529. },
  51530. enumerable: true,
  51531. configurable: true
  51532. });
  51533. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51534. get: function () {
  51535. return EasingFunction._EASINGMODE_EASEOUT;
  51536. },
  51537. enumerable: true,
  51538. configurable: true
  51539. });
  51540. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51541. get: function () {
  51542. return EasingFunction._EASINGMODE_EASEINOUT;
  51543. },
  51544. enumerable: true,
  51545. configurable: true
  51546. });
  51547. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51548. var n = Math.min(Math.max(easingMode, 0), 2);
  51549. this._easingMode = n;
  51550. };
  51551. EasingFunction.prototype.getEasingMode = function () {
  51552. return this._easingMode;
  51553. };
  51554. EasingFunction.prototype.easeInCore = function (gradient) {
  51555. throw new Error('You must implement this method');
  51556. };
  51557. EasingFunction.prototype.ease = function (gradient) {
  51558. switch (this._easingMode) {
  51559. case EasingFunction.EASINGMODE_EASEIN:
  51560. return this.easeInCore(gradient);
  51561. case EasingFunction.EASINGMODE_EASEOUT:
  51562. return (1 - this.easeInCore(1 - gradient));
  51563. }
  51564. if (gradient >= 0.5) {
  51565. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51566. }
  51567. return (this.easeInCore(gradient * 2) * 0.5);
  51568. };
  51569. //Statics
  51570. EasingFunction._EASINGMODE_EASEIN = 0;
  51571. EasingFunction._EASINGMODE_EASEOUT = 1;
  51572. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51573. return EasingFunction;
  51574. }());
  51575. BABYLON.EasingFunction = EasingFunction;
  51576. var CircleEase = /** @class */ (function (_super) {
  51577. __extends(CircleEase, _super);
  51578. function CircleEase() {
  51579. return _super !== null && _super.apply(this, arguments) || this;
  51580. }
  51581. CircleEase.prototype.easeInCore = function (gradient) {
  51582. gradient = Math.max(0, Math.min(1, gradient));
  51583. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51584. };
  51585. return CircleEase;
  51586. }(EasingFunction));
  51587. BABYLON.CircleEase = CircleEase;
  51588. var BackEase = /** @class */ (function (_super) {
  51589. __extends(BackEase, _super);
  51590. function BackEase(amplitude) {
  51591. if (amplitude === void 0) { amplitude = 1; }
  51592. var _this = _super.call(this) || this;
  51593. _this.amplitude = amplitude;
  51594. return _this;
  51595. }
  51596. BackEase.prototype.easeInCore = function (gradient) {
  51597. var num = Math.max(0, this.amplitude);
  51598. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51599. };
  51600. return BackEase;
  51601. }(EasingFunction));
  51602. BABYLON.BackEase = BackEase;
  51603. var BounceEase = /** @class */ (function (_super) {
  51604. __extends(BounceEase, _super);
  51605. function BounceEase(bounces, bounciness) {
  51606. if (bounces === void 0) { bounces = 3; }
  51607. if (bounciness === void 0) { bounciness = 2; }
  51608. var _this = _super.call(this) || this;
  51609. _this.bounces = bounces;
  51610. _this.bounciness = bounciness;
  51611. return _this;
  51612. }
  51613. BounceEase.prototype.easeInCore = function (gradient) {
  51614. var y = Math.max(0.0, this.bounces);
  51615. var bounciness = this.bounciness;
  51616. if (bounciness <= 1.0) {
  51617. bounciness = 1.001;
  51618. }
  51619. var num9 = Math.pow(bounciness, y);
  51620. var num5 = 1.0 - bounciness;
  51621. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51622. var num15 = gradient * num4;
  51623. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51624. var num3 = Math.floor(num65);
  51625. var num13 = num3 + 1.0;
  51626. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51627. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51628. var num7 = (num8 + num12) * 0.5;
  51629. var num6 = gradient - num7;
  51630. var num2 = num7 - num8;
  51631. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51632. };
  51633. return BounceEase;
  51634. }(EasingFunction));
  51635. BABYLON.BounceEase = BounceEase;
  51636. var CubicEase = /** @class */ (function (_super) {
  51637. __extends(CubicEase, _super);
  51638. function CubicEase() {
  51639. return _super !== null && _super.apply(this, arguments) || this;
  51640. }
  51641. CubicEase.prototype.easeInCore = function (gradient) {
  51642. return (gradient * gradient * gradient);
  51643. };
  51644. return CubicEase;
  51645. }(EasingFunction));
  51646. BABYLON.CubicEase = CubicEase;
  51647. var ElasticEase = /** @class */ (function (_super) {
  51648. __extends(ElasticEase, _super);
  51649. function ElasticEase(oscillations, springiness) {
  51650. if (oscillations === void 0) { oscillations = 3; }
  51651. if (springiness === void 0) { springiness = 3; }
  51652. var _this = _super.call(this) || this;
  51653. _this.oscillations = oscillations;
  51654. _this.springiness = springiness;
  51655. return _this;
  51656. }
  51657. ElasticEase.prototype.easeInCore = function (gradient) {
  51658. var num2;
  51659. var num3 = Math.max(0.0, this.oscillations);
  51660. var num = Math.max(0.0, this.springiness);
  51661. if (num == 0) {
  51662. num2 = gradient;
  51663. }
  51664. else {
  51665. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51666. }
  51667. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51668. };
  51669. return ElasticEase;
  51670. }(EasingFunction));
  51671. BABYLON.ElasticEase = ElasticEase;
  51672. var ExponentialEase = /** @class */ (function (_super) {
  51673. __extends(ExponentialEase, _super);
  51674. function ExponentialEase(exponent) {
  51675. if (exponent === void 0) { exponent = 2; }
  51676. var _this = _super.call(this) || this;
  51677. _this.exponent = exponent;
  51678. return _this;
  51679. }
  51680. ExponentialEase.prototype.easeInCore = function (gradient) {
  51681. if (this.exponent <= 0) {
  51682. return gradient;
  51683. }
  51684. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51685. };
  51686. return ExponentialEase;
  51687. }(EasingFunction));
  51688. BABYLON.ExponentialEase = ExponentialEase;
  51689. var PowerEase = /** @class */ (function (_super) {
  51690. __extends(PowerEase, _super);
  51691. function PowerEase(power) {
  51692. if (power === void 0) { power = 2; }
  51693. var _this = _super.call(this) || this;
  51694. _this.power = power;
  51695. return _this;
  51696. }
  51697. PowerEase.prototype.easeInCore = function (gradient) {
  51698. var y = Math.max(0.0, this.power);
  51699. return Math.pow(gradient, y);
  51700. };
  51701. return PowerEase;
  51702. }(EasingFunction));
  51703. BABYLON.PowerEase = PowerEase;
  51704. var QuadraticEase = /** @class */ (function (_super) {
  51705. __extends(QuadraticEase, _super);
  51706. function QuadraticEase() {
  51707. return _super !== null && _super.apply(this, arguments) || this;
  51708. }
  51709. QuadraticEase.prototype.easeInCore = function (gradient) {
  51710. return (gradient * gradient);
  51711. };
  51712. return QuadraticEase;
  51713. }(EasingFunction));
  51714. BABYLON.QuadraticEase = QuadraticEase;
  51715. var QuarticEase = /** @class */ (function (_super) {
  51716. __extends(QuarticEase, _super);
  51717. function QuarticEase() {
  51718. return _super !== null && _super.apply(this, arguments) || this;
  51719. }
  51720. QuarticEase.prototype.easeInCore = function (gradient) {
  51721. return (gradient * gradient * gradient * gradient);
  51722. };
  51723. return QuarticEase;
  51724. }(EasingFunction));
  51725. BABYLON.QuarticEase = QuarticEase;
  51726. var QuinticEase = /** @class */ (function (_super) {
  51727. __extends(QuinticEase, _super);
  51728. function QuinticEase() {
  51729. return _super !== null && _super.apply(this, arguments) || this;
  51730. }
  51731. QuinticEase.prototype.easeInCore = function (gradient) {
  51732. return (gradient * gradient * gradient * gradient * gradient);
  51733. };
  51734. return QuinticEase;
  51735. }(EasingFunction));
  51736. BABYLON.QuinticEase = QuinticEase;
  51737. var SineEase = /** @class */ (function (_super) {
  51738. __extends(SineEase, _super);
  51739. function SineEase() {
  51740. return _super !== null && _super.apply(this, arguments) || this;
  51741. }
  51742. SineEase.prototype.easeInCore = function (gradient) {
  51743. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51744. };
  51745. return SineEase;
  51746. }(EasingFunction));
  51747. BABYLON.SineEase = SineEase;
  51748. var BezierCurveEase = /** @class */ (function (_super) {
  51749. __extends(BezierCurveEase, _super);
  51750. function BezierCurveEase(x1, y1, x2, y2) {
  51751. if (x1 === void 0) { x1 = 0; }
  51752. if (y1 === void 0) { y1 = 0; }
  51753. if (x2 === void 0) { x2 = 1; }
  51754. if (y2 === void 0) { y2 = 1; }
  51755. var _this = _super.call(this) || this;
  51756. _this.x1 = x1;
  51757. _this.y1 = y1;
  51758. _this.x2 = x2;
  51759. _this.y2 = y2;
  51760. return _this;
  51761. }
  51762. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51763. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51764. };
  51765. return BezierCurveEase;
  51766. }(EasingFunction));
  51767. BABYLON.BezierCurveEase = BezierCurveEase;
  51768. })(BABYLON || (BABYLON = {}));
  51769. //# sourceMappingURL=babylon.easing.js.map
  51770. var BABYLON;
  51771. (function (BABYLON) {
  51772. /**
  51773. * A Condition applied to an Action
  51774. */
  51775. var Condition = /** @class */ (function () {
  51776. /**
  51777. * Creates a new Condition
  51778. * @param actionManager the manager of the action the condition is applied to
  51779. */
  51780. function Condition(actionManager) {
  51781. this._actionManager = actionManager;
  51782. }
  51783. /**
  51784. * Check if the current condition is valid
  51785. * @returns a boolean
  51786. */
  51787. Condition.prototype.isValid = function () {
  51788. return true;
  51789. };
  51790. /**
  51791. * Internal only
  51792. * @hidden
  51793. */
  51794. Condition.prototype._getProperty = function (propertyPath) {
  51795. return this._actionManager._getProperty(propertyPath);
  51796. };
  51797. /**
  51798. * Internal only
  51799. * @hidden
  51800. */
  51801. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51802. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51803. };
  51804. /**
  51805. * Serialize placeholder for child classes
  51806. * @returns the serialized object
  51807. */
  51808. Condition.prototype.serialize = function () {
  51809. };
  51810. /**
  51811. * Internal only
  51812. * @hidden
  51813. */
  51814. Condition.prototype._serialize = function (serializedCondition) {
  51815. return {
  51816. type: 2,
  51817. children: [],
  51818. name: serializedCondition.name,
  51819. properties: serializedCondition.properties
  51820. };
  51821. };
  51822. return Condition;
  51823. }());
  51824. BABYLON.Condition = Condition;
  51825. /**
  51826. * Defines specific conditional operators as extensions of Condition
  51827. */
  51828. var ValueCondition = /** @class */ (function (_super) {
  51829. __extends(ValueCondition, _super);
  51830. /**
  51831. * Creates a new ValueCondition
  51832. * @param actionManager manager for the action the condition applies to
  51833. * @param target for the action
  51834. * @param propertyPath path to specify the property of the target the conditional operator uses
  51835. * @param value the value compared by the conditional operator against the current value of the property
  51836. * @param operator the conditional operator, default ValueCondition.IsEqual
  51837. */
  51838. function ValueCondition(actionManager, target,
  51839. /** path to specify the property of the target the conditional operator uses */
  51840. propertyPath,
  51841. /** the value compared by the conditional operator against the current value of the property */
  51842. value,
  51843. /** the conditional operator, default ValueCondition.IsEqual */
  51844. operator) {
  51845. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51846. var _this = _super.call(this, actionManager) || this;
  51847. _this.propertyPath = propertyPath;
  51848. _this.value = value;
  51849. _this.operator = operator;
  51850. _this._target = target;
  51851. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51852. _this._property = _this._getProperty(_this.propertyPath);
  51853. return _this;
  51854. }
  51855. Object.defineProperty(ValueCondition, "IsEqual", {
  51856. /**
  51857. * returns the number for IsEqual
  51858. */
  51859. get: function () {
  51860. return ValueCondition._IsEqual;
  51861. },
  51862. enumerable: true,
  51863. configurable: true
  51864. });
  51865. Object.defineProperty(ValueCondition, "IsDifferent", {
  51866. /**
  51867. * Returns the number for IsDifferent
  51868. */
  51869. get: function () {
  51870. return ValueCondition._IsDifferent;
  51871. },
  51872. enumerable: true,
  51873. configurable: true
  51874. });
  51875. Object.defineProperty(ValueCondition, "IsGreater", {
  51876. /**
  51877. * Returns the number for IsGreater
  51878. */
  51879. get: function () {
  51880. return ValueCondition._IsGreater;
  51881. },
  51882. enumerable: true,
  51883. configurable: true
  51884. });
  51885. Object.defineProperty(ValueCondition, "IsLesser", {
  51886. /**
  51887. * Returns the number for IsLesser
  51888. */
  51889. get: function () {
  51890. return ValueCondition._IsLesser;
  51891. },
  51892. enumerable: true,
  51893. configurable: true
  51894. });
  51895. /**
  51896. * Compares the given value with the property value for the specified conditional operator
  51897. * @returns the result of the comparison
  51898. */
  51899. ValueCondition.prototype.isValid = function () {
  51900. switch (this.operator) {
  51901. case ValueCondition.IsGreater:
  51902. return this._effectiveTarget[this._property] > this.value;
  51903. case ValueCondition.IsLesser:
  51904. return this._effectiveTarget[this._property] < this.value;
  51905. case ValueCondition.IsEqual:
  51906. case ValueCondition.IsDifferent:
  51907. var check;
  51908. if (this.value.equals) {
  51909. check = this.value.equals(this._effectiveTarget[this._property]);
  51910. }
  51911. else {
  51912. check = this.value === this._effectiveTarget[this._property];
  51913. }
  51914. return this.operator === ValueCondition.IsEqual ? check : !check;
  51915. }
  51916. return false;
  51917. };
  51918. /**
  51919. * Serialize the ValueCondition into a JSON compatible object
  51920. * @returns serialization object
  51921. */
  51922. ValueCondition.prototype.serialize = function () {
  51923. return this._serialize({
  51924. name: "ValueCondition",
  51925. properties: [
  51926. BABYLON.Action._GetTargetProperty(this._target),
  51927. { name: "propertyPath", value: this.propertyPath },
  51928. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51929. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51930. ]
  51931. });
  51932. };
  51933. /**
  51934. * Gets the name of the conditional operator for the ValueCondition
  51935. * @param operator the conditional operator
  51936. * @returns the name
  51937. */
  51938. ValueCondition.GetOperatorName = function (operator) {
  51939. switch (operator) {
  51940. case ValueCondition._IsEqual: return "IsEqual";
  51941. case ValueCondition._IsDifferent: return "IsDifferent";
  51942. case ValueCondition._IsGreater: return "IsGreater";
  51943. case ValueCondition._IsLesser: return "IsLesser";
  51944. default: return "";
  51945. }
  51946. };
  51947. /**
  51948. * Internal only
  51949. * @hidden
  51950. */
  51951. ValueCondition._IsEqual = 0;
  51952. /**
  51953. * Internal only
  51954. * @hidden
  51955. */
  51956. ValueCondition._IsDifferent = 1;
  51957. /**
  51958. * Internal only
  51959. * @hidden
  51960. */
  51961. ValueCondition._IsGreater = 2;
  51962. /**
  51963. * Internal only
  51964. * @hidden
  51965. */
  51966. ValueCondition._IsLesser = 3;
  51967. return ValueCondition;
  51968. }(Condition));
  51969. BABYLON.ValueCondition = ValueCondition;
  51970. /**
  51971. * Defines a predicate condition as an extension of Condition
  51972. */
  51973. var PredicateCondition = /** @class */ (function (_super) {
  51974. __extends(PredicateCondition, _super);
  51975. /**
  51976. * Creates a new PredicateCondition
  51977. * @param actionManager manager for the action the condition applies to
  51978. * @param predicate defines the predicate function used to validate the condition
  51979. */
  51980. function PredicateCondition(actionManager,
  51981. /** defines the predicate function used to validate the condition */
  51982. predicate) {
  51983. var _this = _super.call(this, actionManager) || this;
  51984. _this.predicate = predicate;
  51985. return _this;
  51986. }
  51987. /**
  51988. * @returns the validity of the predicate condition
  51989. */
  51990. PredicateCondition.prototype.isValid = function () {
  51991. return this.predicate();
  51992. };
  51993. return PredicateCondition;
  51994. }(Condition));
  51995. BABYLON.PredicateCondition = PredicateCondition;
  51996. /**
  51997. * Defines a state condition as an extension of Condition
  51998. */
  51999. var StateCondition = /** @class */ (function (_super) {
  52000. __extends(StateCondition, _super);
  52001. /**
  52002. * Creates a new StateCondition
  52003. * @param actionManager manager for the action the condition applies to
  52004. * @param target of the condition
  52005. * @param value to compare with target state
  52006. */
  52007. function StateCondition(actionManager, target, value) {
  52008. var _this = _super.call(this, actionManager) || this;
  52009. _this.value = value;
  52010. _this._target = target;
  52011. return _this;
  52012. }
  52013. /**
  52014. * @returns the validity of the state
  52015. */
  52016. StateCondition.prototype.isValid = function () {
  52017. return this._target.state === this.value;
  52018. };
  52019. /**
  52020. * Serialize the StateCondition into a JSON compatible object
  52021. * @returns serialization object
  52022. */
  52023. StateCondition.prototype.serialize = function () {
  52024. return this._serialize({
  52025. name: "StateCondition",
  52026. properties: [
  52027. BABYLON.Action._GetTargetProperty(this._target),
  52028. { name: "value", value: this.value }
  52029. ]
  52030. });
  52031. };
  52032. return StateCondition;
  52033. }(Condition));
  52034. BABYLON.StateCondition = StateCondition;
  52035. })(BABYLON || (BABYLON = {}));
  52036. //# sourceMappingURL=babylon.condition.js.map
  52037. var BABYLON;
  52038. (function (BABYLON) {
  52039. /**
  52040. * The action to be carried out following a trigger
  52041. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52042. */
  52043. var Action = /** @class */ (function () {
  52044. /**
  52045. * Creates a new Action
  52046. * @param triggerOptions the trigger, with or without parameters, for the action
  52047. * @param condition an optional determinant of action
  52048. */
  52049. function Action(
  52050. /** the trigger, with or without parameters, for the action */
  52051. triggerOptions, condition) {
  52052. this.triggerOptions = triggerOptions;
  52053. /**
  52054. * An event triggered prior to action being executed.
  52055. */
  52056. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52057. if (triggerOptions.parameter) {
  52058. this.trigger = triggerOptions.trigger;
  52059. this._triggerParameter = triggerOptions.parameter;
  52060. }
  52061. else {
  52062. this.trigger = triggerOptions;
  52063. }
  52064. this._nextActiveAction = this;
  52065. this._condition = condition;
  52066. }
  52067. /**
  52068. * Internal only
  52069. * @hidden
  52070. */
  52071. Action.prototype._prepare = function () {
  52072. };
  52073. /**
  52074. * Gets the trigger parameters
  52075. * @returns the trigger parameters
  52076. */
  52077. Action.prototype.getTriggerParameter = function () {
  52078. return this._triggerParameter;
  52079. };
  52080. /**
  52081. * Internal only - executes current action event
  52082. * @hidden
  52083. */
  52084. Action.prototype._executeCurrent = function (evt) {
  52085. if (this._nextActiveAction._condition) {
  52086. var condition = this._nextActiveAction._condition;
  52087. var currentRenderId = this._actionManager.getScene().getRenderId();
  52088. // We cache the current evaluation for the current frame
  52089. if (condition._evaluationId === currentRenderId) {
  52090. if (!condition._currentResult) {
  52091. return;
  52092. }
  52093. }
  52094. else {
  52095. condition._evaluationId = currentRenderId;
  52096. if (!condition.isValid()) {
  52097. condition._currentResult = false;
  52098. return;
  52099. }
  52100. condition._currentResult = true;
  52101. }
  52102. }
  52103. this.onBeforeExecuteObservable.notifyObservers(this);
  52104. this._nextActiveAction.execute(evt);
  52105. this.skipToNextActiveAction();
  52106. };
  52107. /**
  52108. * Execute placeholder for child classes
  52109. * @param evt optional action event
  52110. */
  52111. Action.prototype.execute = function (evt) {
  52112. };
  52113. /**
  52114. * Skips to next active action
  52115. */
  52116. Action.prototype.skipToNextActiveAction = function () {
  52117. if (this._nextActiveAction._child) {
  52118. if (!this._nextActiveAction._child._actionManager) {
  52119. this._nextActiveAction._child._actionManager = this._actionManager;
  52120. }
  52121. this._nextActiveAction = this._nextActiveAction._child;
  52122. }
  52123. else {
  52124. this._nextActiveAction = this;
  52125. }
  52126. };
  52127. /**
  52128. * Adds action to chain of actions, may be a DoNothingAction
  52129. * @param action defines the next action to execute
  52130. * @returns The action passed in
  52131. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52132. */
  52133. Action.prototype.then = function (action) {
  52134. this._child = action;
  52135. action._actionManager = this._actionManager;
  52136. action._prepare();
  52137. return action;
  52138. };
  52139. /**
  52140. * Internal only
  52141. * @hidden
  52142. */
  52143. Action.prototype._getProperty = function (propertyPath) {
  52144. return this._actionManager._getProperty(propertyPath);
  52145. };
  52146. /**
  52147. * Internal only
  52148. * @hidden
  52149. */
  52150. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52151. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52152. };
  52153. /**
  52154. * Serialize placeholder for child classes
  52155. * @param parent of child
  52156. * @returns the serialized object
  52157. */
  52158. Action.prototype.serialize = function (parent) {
  52159. };
  52160. /**
  52161. * Internal only called by serialize
  52162. * @hidden
  52163. */
  52164. Action.prototype._serialize = function (serializedAction, parent) {
  52165. var serializationObject = {
  52166. type: 1,
  52167. children: [],
  52168. name: serializedAction.name,
  52169. properties: serializedAction.properties || []
  52170. };
  52171. // Serialize child
  52172. if (this._child) {
  52173. this._child.serialize(serializationObject);
  52174. }
  52175. // Check if "this" has a condition
  52176. if (this._condition) {
  52177. var serializedCondition = this._condition.serialize();
  52178. serializedCondition.children.push(serializationObject);
  52179. if (parent) {
  52180. parent.children.push(serializedCondition);
  52181. }
  52182. return serializedCondition;
  52183. }
  52184. if (parent) {
  52185. parent.children.push(serializationObject);
  52186. }
  52187. return serializationObject;
  52188. };
  52189. /**
  52190. * Internal only
  52191. * @hidden
  52192. */
  52193. Action._SerializeValueAsString = function (value) {
  52194. if (typeof value === "number") {
  52195. return value.toString();
  52196. }
  52197. if (typeof value === "boolean") {
  52198. return value ? "true" : "false";
  52199. }
  52200. if (value instanceof BABYLON.Vector2) {
  52201. return value.x + ", " + value.y;
  52202. }
  52203. if (value instanceof BABYLON.Vector3) {
  52204. return value.x + ", " + value.y + ", " + value.z;
  52205. }
  52206. if (value instanceof BABYLON.Color3) {
  52207. return value.r + ", " + value.g + ", " + value.b;
  52208. }
  52209. if (value instanceof BABYLON.Color4) {
  52210. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52211. }
  52212. return value; // string
  52213. };
  52214. /**
  52215. * Internal only
  52216. * @hidden
  52217. */
  52218. Action._GetTargetProperty = function (target) {
  52219. return {
  52220. name: "target",
  52221. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52222. : target instanceof BABYLON.Light ? "LightProperties"
  52223. : target instanceof BABYLON.Camera ? "CameraProperties"
  52224. : "SceneProperties",
  52225. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52226. };
  52227. };
  52228. return Action;
  52229. }());
  52230. BABYLON.Action = Action;
  52231. })(BABYLON || (BABYLON = {}));
  52232. //# sourceMappingURL=babylon.action.js.map
  52233. var BABYLON;
  52234. (function (BABYLON) {
  52235. /**
  52236. * ActionEvent is the event being sent when an action is triggered.
  52237. */
  52238. var ActionEvent = /** @class */ (function () {
  52239. /**
  52240. * Creates a new ActionEvent
  52241. * @param source The mesh or sprite that triggered the action
  52242. * @param pointerX The X mouse cursor position at the time of the event
  52243. * @param pointerY The Y mouse cursor position at the time of the event
  52244. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52245. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52246. * @param additionalData additional data for the event
  52247. */
  52248. function ActionEvent(
  52249. /** The mesh or sprite that triggered the action */
  52250. source,
  52251. /** The X mouse cursor position at the time of the event */
  52252. pointerX,
  52253. /** The Y mouse cursor position at the time of the event */
  52254. pointerY,
  52255. /** The mesh that is currently pointed at (can be null) */
  52256. meshUnderPointer,
  52257. /** the original (browser) event that triggered the ActionEvent */
  52258. sourceEvent,
  52259. /** additional data for the event */
  52260. additionalData) {
  52261. this.source = source;
  52262. this.pointerX = pointerX;
  52263. this.pointerY = pointerY;
  52264. this.meshUnderPointer = meshUnderPointer;
  52265. this.sourceEvent = sourceEvent;
  52266. this.additionalData = additionalData;
  52267. }
  52268. /**
  52269. * Helper function to auto-create an ActionEvent from a source mesh.
  52270. * @param source The source mesh that triggered the event
  52271. * @param evt The original (browser) event
  52272. * @param additionalData additional data for the event
  52273. * @returns the new ActionEvent
  52274. */
  52275. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52276. var scene = source.getScene();
  52277. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52278. };
  52279. /**
  52280. * Helper function to auto-create an ActionEvent from a source sprite
  52281. * @param source The source sprite that triggered the event
  52282. * @param scene Scene associated with the sprite
  52283. * @param evt The original (browser) event
  52284. * @param additionalData additional data for the event
  52285. * @returns the new ActionEvent
  52286. */
  52287. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52288. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52289. };
  52290. /**
  52291. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52292. * @param scene the scene where the event occurred
  52293. * @param evt The original (browser) event
  52294. * @returns the new ActionEvent
  52295. */
  52296. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52297. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52298. };
  52299. /**
  52300. * Helper function to auto-create an ActionEvent from a primitive
  52301. * @param prim defines the target primitive
  52302. * @param pointerPos defines the pointer position
  52303. * @param evt The original (browser) event
  52304. * @param additionalData additional data for the event
  52305. * @returns the new ActionEvent
  52306. */
  52307. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52308. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52309. };
  52310. return ActionEvent;
  52311. }());
  52312. BABYLON.ActionEvent = ActionEvent;
  52313. /**
  52314. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52315. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52316. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52317. */
  52318. var ActionManager = /** @class */ (function () {
  52319. /**
  52320. * Creates a new action manager
  52321. * @param scene defines the hosting scene
  52322. */
  52323. function ActionManager(scene) {
  52324. // Members
  52325. /** Gets the list of actions */
  52326. this.actions = new Array();
  52327. /** Gets the cursor to use when hovering items */
  52328. this.hoverCursor = '';
  52329. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52330. scene.actionManagers.push(this);
  52331. }
  52332. Object.defineProperty(ActionManager, "NothingTrigger", {
  52333. /**
  52334. * Nothing
  52335. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52336. */
  52337. get: function () {
  52338. return ActionManager._NothingTrigger;
  52339. },
  52340. enumerable: true,
  52341. configurable: true
  52342. });
  52343. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52344. /**
  52345. * On pick
  52346. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52347. */
  52348. get: function () {
  52349. return ActionManager._OnPickTrigger;
  52350. },
  52351. enumerable: true,
  52352. configurable: true
  52353. });
  52354. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52355. /**
  52356. * On left pick
  52357. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52358. */
  52359. get: function () {
  52360. return ActionManager._OnLeftPickTrigger;
  52361. },
  52362. enumerable: true,
  52363. configurable: true
  52364. });
  52365. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52366. /**
  52367. * On right pick
  52368. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52369. */
  52370. get: function () {
  52371. return ActionManager._OnRightPickTrigger;
  52372. },
  52373. enumerable: true,
  52374. configurable: true
  52375. });
  52376. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52377. /**
  52378. * On center pick
  52379. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52380. */
  52381. get: function () {
  52382. return ActionManager._OnCenterPickTrigger;
  52383. },
  52384. enumerable: true,
  52385. configurable: true
  52386. });
  52387. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52388. /**
  52389. * On pick down
  52390. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52391. */
  52392. get: function () {
  52393. return ActionManager._OnPickDownTrigger;
  52394. },
  52395. enumerable: true,
  52396. configurable: true
  52397. });
  52398. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52399. /**
  52400. * On double pick
  52401. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52402. */
  52403. get: function () {
  52404. return ActionManager._OnDoublePickTrigger;
  52405. },
  52406. enumerable: true,
  52407. configurable: true
  52408. });
  52409. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52410. /**
  52411. * On pick up
  52412. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52413. */
  52414. get: function () {
  52415. return ActionManager._OnPickUpTrigger;
  52416. },
  52417. enumerable: true,
  52418. configurable: true
  52419. });
  52420. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52421. /**
  52422. * On pick out.
  52423. * This trigger will only be raised if you also declared a OnPickDown
  52424. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52425. */
  52426. get: function () {
  52427. return ActionManager._OnPickOutTrigger;
  52428. },
  52429. enumerable: true,
  52430. configurable: true
  52431. });
  52432. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52433. /**
  52434. * On long press
  52435. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52436. */
  52437. get: function () {
  52438. return ActionManager._OnLongPressTrigger;
  52439. },
  52440. enumerable: true,
  52441. configurable: true
  52442. });
  52443. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52444. /**
  52445. * On pointer over
  52446. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52447. */
  52448. get: function () {
  52449. return ActionManager._OnPointerOverTrigger;
  52450. },
  52451. enumerable: true,
  52452. configurable: true
  52453. });
  52454. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52455. /**
  52456. * On pointer out
  52457. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52458. */
  52459. get: function () {
  52460. return ActionManager._OnPointerOutTrigger;
  52461. },
  52462. enumerable: true,
  52463. configurable: true
  52464. });
  52465. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52466. /**
  52467. * On every frame
  52468. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52469. */
  52470. get: function () {
  52471. return ActionManager._OnEveryFrameTrigger;
  52472. },
  52473. enumerable: true,
  52474. configurable: true
  52475. });
  52476. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52477. /**
  52478. * On intersection enter
  52479. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52480. */
  52481. get: function () {
  52482. return ActionManager._OnIntersectionEnterTrigger;
  52483. },
  52484. enumerable: true,
  52485. configurable: true
  52486. });
  52487. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52488. /**
  52489. * On intersection exit
  52490. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52491. */
  52492. get: function () {
  52493. return ActionManager._OnIntersectionExitTrigger;
  52494. },
  52495. enumerable: true,
  52496. configurable: true
  52497. });
  52498. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52499. /**
  52500. * On key down
  52501. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52502. */
  52503. get: function () {
  52504. return ActionManager._OnKeyDownTrigger;
  52505. },
  52506. enumerable: true,
  52507. configurable: true
  52508. });
  52509. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52510. /**
  52511. * On key up
  52512. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52513. */
  52514. get: function () {
  52515. return ActionManager._OnKeyUpTrigger;
  52516. },
  52517. enumerable: true,
  52518. configurable: true
  52519. });
  52520. // Methods
  52521. /**
  52522. * Releases all associated resources
  52523. */
  52524. ActionManager.prototype.dispose = function () {
  52525. var index = this._scene.actionManagers.indexOf(this);
  52526. for (var i = 0; i < this.actions.length; i++) {
  52527. var action = this.actions[i];
  52528. ActionManager.Triggers[action.trigger]--;
  52529. if (ActionManager.Triggers[action.trigger] === 0) {
  52530. delete ActionManager.Triggers[action.trigger];
  52531. }
  52532. }
  52533. if (index > -1) {
  52534. this._scene.actionManagers.splice(index, 1);
  52535. }
  52536. };
  52537. /**
  52538. * Gets hosting scene
  52539. * @returns the hosting scene
  52540. */
  52541. ActionManager.prototype.getScene = function () {
  52542. return this._scene;
  52543. };
  52544. /**
  52545. * Does this action manager handles actions of any of the given triggers
  52546. * @param triggers defines the triggers to be tested
  52547. * @return a boolean indicating whether one (or more) of the triggers is handled
  52548. */
  52549. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52550. for (var index = 0; index < this.actions.length; index++) {
  52551. var action = this.actions[index];
  52552. if (triggers.indexOf(action.trigger) > -1) {
  52553. return true;
  52554. }
  52555. }
  52556. return false;
  52557. };
  52558. /**
  52559. * Does this action manager handles actions of a given trigger
  52560. * @param trigger defines the trigger to be tested
  52561. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52562. * @return whether the trigger is handled
  52563. */
  52564. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52565. for (var index = 0; index < this.actions.length; index++) {
  52566. var action = this.actions[index];
  52567. if (action.trigger === trigger) {
  52568. if (parameterPredicate) {
  52569. if (parameterPredicate(action.getTriggerParameter())) {
  52570. return true;
  52571. }
  52572. }
  52573. else {
  52574. return true;
  52575. }
  52576. }
  52577. }
  52578. return false;
  52579. };
  52580. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52581. /**
  52582. * Does this action manager has pointer triggers
  52583. */
  52584. get: function () {
  52585. for (var index = 0; index < this.actions.length; index++) {
  52586. var action = this.actions[index];
  52587. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52588. return true;
  52589. }
  52590. }
  52591. return false;
  52592. },
  52593. enumerable: true,
  52594. configurable: true
  52595. });
  52596. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52597. /**
  52598. * Does this action manager has pick triggers
  52599. */
  52600. get: function () {
  52601. for (var index = 0; index < this.actions.length; index++) {
  52602. var action = this.actions[index];
  52603. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52604. return true;
  52605. }
  52606. }
  52607. return false;
  52608. },
  52609. enumerable: true,
  52610. configurable: true
  52611. });
  52612. Object.defineProperty(ActionManager, "HasTriggers", {
  52613. /**
  52614. * Does exist one action manager with at least one trigger
  52615. **/
  52616. get: function () {
  52617. for (var t in ActionManager.Triggers) {
  52618. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52619. return true;
  52620. }
  52621. }
  52622. return false;
  52623. },
  52624. enumerable: true,
  52625. configurable: true
  52626. });
  52627. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52628. /**
  52629. * Does exist one action manager with at least one pick trigger
  52630. **/
  52631. get: function () {
  52632. for (var t in ActionManager.Triggers) {
  52633. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52634. var t_int = parseInt(t);
  52635. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52636. return true;
  52637. }
  52638. }
  52639. }
  52640. return false;
  52641. },
  52642. enumerable: true,
  52643. configurable: true
  52644. });
  52645. /**
  52646. * Does exist one action manager that handles actions of a given trigger
  52647. * @param trigger defines the trigger to be tested
  52648. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52649. **/
  52650. ActionManager.HasSpecificTrigger = function (trigger) {
  52651. for (var t in ActionManager.Triggers) {
  52652. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52653. var t_int = parseInt(t);
  52654. if (t_int === trigger) {
  52655. return true;
  52656. }
  52657. }
  52658. }
  52659. return false;
  52660. };
  52661. /**
  52662. * Registers an action to this action manager
  52663. * @param action defines the action to be registered
  52664. * @return the action amended (prepared) after registration
  52665. */
  52666. ActionManager.prototype.registerAction = function (action) {
  52667. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52668. if (this.getScene().actionManager !== this) {
  52669. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52670. return null;
  52671. }
  52672. }
  52673. this.actions.push(action);
  52674. if (ActionManager.Triggers[action.trigger]) {
  52675. ActionManager.Triggers[action.trigger]++;
  52676. }
  52677. else {
  52678. ActionManager.Triggers[action.trigger] = 1;
  52679. }
  52680. action._actionManager = this;
  52681. action._prepare();
  52682. return action;
  52683. };
  52684. /**
  52685. * Unregisters an action to this action manager
  52686. * @param action defines the action to be unregistered
  52687. * @return a boolean indicating whether the action has been unregistered
  52688. */
  52689. ActionManager.prototype.unregisterAction = function (action) {
  52690. var index = this.actions.indexOf(action);
  52691. if (index !== -1) {
  52692. this.actions.splice(index, 1);
  52693. ActionManager.Triggers[action.trigger] -= 1;
  52694. if (ActionManager.Triggers[action.trigger] === 0) {
  52695. delete ActionManager.Triggers[action.trigger];
  52696. }
  52697. delete action._actionManager;
  52698. return true;
  52699. }
  52700. return false;
  52701. };
  52702. /**
  52703. * Process a specific trigger
  52704. * @param trigger defines the trigger to process
  52705. * @param evt defines the event details to be processed
  52706. */
  52707. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52708. for (var index = 0; index < this.actions.length; index++) {
  52709. var action = this.actions[index];
  52710. if (action.trigger === trigger) {
  52711. if (evt) {
  52712. if (trigger === ActionManager.OnKeyUpTrigger
  52713. || trigger === ActionManager.OnKeyDownTrigger) {
  52714. var parameter = action.getTriggerParameter();
  52715. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52716. if (!parameter.toLowerCase) {
  52717. continue;
  52718. }
  52719. var lowerCase = parameter.toLowerCase();
  52720. if (lowerCase !== evt.sourceEvent.key) {
  52721. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52722. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52723. if (actualkey !== lowerCase) {
  52724. continue;
  52725. }
  52726. }
  52727. }
  52728. }
  52729. }
  52730. action._executeCurrent(evt);
  52731. }
  52732. }
  52733. };
  52734. /** @hidden */
  52735. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52736. var properties = propertyPath.split(".");
  52737. for (var index = 0; index < properties.length - 1; index++) {
  52738. target = target[properties[index]];
  52739. }
  52740. return target;
  52741. };
  52742. /** @hidden */
  52743. ActionManager.prototype._getProperty = function (propertyPath) {
  52744. var properties = propertyPath.split(".");
  52745. return properties[properties.length - 1];
  52746. };
  52747. /**
  52748. * Serialize this manager to a JSON object
  52749. * @param name defines the property name to store this manager
  52750. * @returns a JSON representation of this manager
  52751. */
  52752. ActionManager.prototype.serialize = function (name) {
  52753. var root = {
  52754. children: new Array(),
  52755. name: name,
  52756. type: 3,
  52757. properties: new Array() // Empty for root but required
  52758. };
  52759. for (var i = 0; i < this.actions.length; i++) {
  52760. var triggerObject = {
  52761. type: 0,
  52762. children: new Array(),
  52763. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52764. properties: new Array()
  52765. };
  52766. var triggerOptions = this.actions[i].triggerOptions;
  52767. if (triggerOptions && typeof triggerOptions !== "number") {
  52768. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52769. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52770. }
  52771. else {
  52772. var parameter = {};
  52773. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52774. if (triggerOptions.parameter.mesh) {
  52775. parameter._meshId = triggerOptions.parameter.mesh.id;
  52776. }
  52777. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52778. }
  52779. }
  52780. // Serialize child action, recursively
  52781. this.actions[i].serialize(triggerObject);
  52782. // Add serialized trigger
  52783. root.children.push(triggerObject);
  52784. }
  52785. return root;
  52786. };
  52787. /**
  52788. * Creates a new ActionManager from a JSON data
  52789. * @param parsedActions defines the JSON data to read from
  52790. * @param object defines the hosting mesh
  52791. * @param scene defines the hosting scene
  52792. */
  52793. ActionManager.Parse = function (parsedActions, object, scene) {
  52794. var actionManager = new ActionManager(scene);
  52795. if (object === null)
  52796. scene.actionManager = actionManager;
  52797. else
  52798. object.actionManager = actionManager;
  52799. // instanciate a new object
  52800. var instanciate = function (name, params) {
  52801. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52802. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52803. newInstance.constructor.apply(newInstance, params);
  52804. return newInstance;
  52805. };
  52806. var parseParameter = function (name, value, target, propertyPath) {
  52807. if (propertyPath === null) {
  52808. // String, boolean or float
  52809. var floatValue = parseFloat(value);
  52810. if (value === "true" || value === "false")
  52811. return value === "true";
  52812. else
  52813. return isNaN(floatValue) ? value : floatValue;
  52814. }
  52815. var effectiveTarget = propertyPath.split(".");
  52816. var values = value.split(",");
  52817. // Get effective Target
  52818. for (var i = 0; i < effectiveTarget.length; i++) {
  52819. target = target[effectiveTarget[i]];
  52820. }
  52821. // Return appropriate value with its type
  52822. if (typeof (target) === "boolean")
  52823. return values[0] === "true";
  52824. if (typeof (target) === "string")
  52825. return values[0];
  52826. // Parameters with multiple values such as Vector3 etc.
  52827. var split = new Array();
  52828. for (var i = 0; i < values.length; i++)
  52829. split.push(parseFloat(values[i]));
  52830. if (target instanceof BABYLON.Vector3)
  52831. return BABYLON.Vector3.FromArray(split);
  52832. if (target instanceof BABYLON.Vector4)
  52833. return BABYLON.Vector4.FromArray(split);
  52834. if (target instanceof BABYLON.Color3)
  52835. return BABYLON.Color3.FromArray(split);
  52836. if (target instanceof BABYLON.Color4)
  52837. return BABYLON.Color4.FromArray(split);
  52838. return parseFloat(values[0]);
  52839. };
  52840. // traverse graph per trigger
  52841. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52842. if (combineArray === void 0) { combineArray = null; }
  52843. if (parsedAction.detached)
  52844. return;
  52845. var parameters = new Array();
  52846. var target = null;
  52847. var propertyPath = null;
  52848. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52849. // Parameters
  52850. if (parsedAction.type === 2)
  52851. parameters.push(actionManager);
  52852. else
  52853. parameters.push(trigger);
  52854. if (combine) {
  52855. var actions = new Array();
  52856. for (var j = 0; j < parsedAction.combine.length; j++) {
  52857. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52858. }
  52859. parameters.push(actions);
  52860. }
  52861. else {
  52862. for (var i = 0; i < parsedAction.properties.length; i++) {
  52863. var value = parsedAction.properties[i].value;
  52864. var name = parsedAction.properties[i].name;
  52865. var targetType = parsedAction.properties[i].targetType;
  52866. if (name === "target")
  52867. if (targetType !== null && targetType === "SceneProperties")
  52868. value = target = scene;
  52869. else
  52870. value = target = scene.getNodeByName(value);
  52871. else if (name === "parent")
  52872. value = scene.getNodeByName(value);
  52873. else if (name === "sound")
  52874. value = scene.getSoundByName(value);
  52875. else if (name !== "propertyPath") {
  52876. if (parsedAction.type === 2 && name === "operator")
  52877. value = BABYLON.ValueCondition[value];
  52878. else
  52879. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52880. }
  52881. else {
  52882. propertyPath = value;
  52883. }
  52884. parameters.push(value);
  52885. }
  52886. }
  52887. if (combineArray === null) {
  52888. parameters.push(condition);
  52889. }
  52890. else {
  52891. parameters.push(null);
  52892. }
  52893. // If interpolate value action
  52894. if (parsedAction.name === "InterpolateValueAction") {
  52895. var param = parameters[parameters.length - 2];
  52896. parameters[parameters.length - 1] = param;
  52897. parameters[parameters.length - 2] = condition;
  52898. }
  52899. // Action or condition(s) and not CombineAction
  52900. var newAction = instanciate(parsedAction.name, parameters);
  52901. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52902. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52903. if (action)
  52904. action.then(nothing);
  52905. else
  52906. actionManager.registerAction(nothing);
  52907. action = nothing;
  52908. }
  52909. if (combineArray === null) {
  52910. if (newAction instanceof BABYLON.Condition) {
  52911. condition = newAction;
  52912. newAction = action;
  52913. }
  52914. else {
  52915. condition = null;
  52916. if (action)
  52917. action.then(newAction);
  52918. else
  52919. actionManager.registerAction(newAction);
  52920. }
  52921. }
  52922. else {
  52923. combineArray.push(newAction);
  52924. }
  52925. for (var i = 0; i < parsedAction.children.length; i++)
  52926. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52927. };
  52928. // triggers
  52929. for (var i = 0; i < parsedActions.children.length; i++) {
  52930. var triggerParams;
  52931. var trigger = parsedActions.children[i];
  52932. if (trigger.properties.length > 0) {
  52933. var param = trigger.properties[0].value;
  52934. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52935. if (value._meshId) {
  52936. value.mesh = scene.getMeshByID(value._meshId);
  52937. }
  52938. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52939. }
  52940. else
  52941. triggerParams = ActionManager[trigger.name];
  52942. for (var j = 0; j < trigger.children.length; j++) {
  52943. if (!trigger.detached)
  52944. traverse(trigger.children[j], triggerParams, null, null);
  52945. }
  52946. }
  52947. };
  52948. /**
  52949. * Get a trigger name by index
  52950. * @param trigger defines the trigger index
  52951. * @returns a trigger name
  52952. */
  52953. ActionManager.GetTriggerName = function (trigger) {
  52954. switch (trigger) {
  52955. case 0: return "NothingTrigger";
  52956. case 1: return "OnPickTrigger";
  52957. case 2: return "OnLeftPickTrigger";
  52958. case 3: return "OnRightPickTrigger";
  52959. case 4: return "OnCenterPickTrigger";
  52960. case 5: return "OnPickDownTrigger";
  52961. case 6: return "OnPickUpTrigger";
  52962. case 7: return "OnLongPressTrigger";
  52963. case 8: return "OnPointerOverTrigger";
  52964. case 9: return "OnPointerOutTrigger";
  52965. case 10: return "OnEveryFrameTrigger";
  52966. case 11: return "OnIntersectionEnterTrigger";
  52967. case 12: return "OnIntersectionExitTrigger";
  52968. case 13: return "OnKeyDownTrigger";
  52969. case 14: return "OnKeyUpTrigger";
  52970. case 15: return "OnPickOutTrigger";
  52971. default: return "";
  52972. }
  52973. };
  52974. // Statics
  52975. ActionManager._NothingTrigger = 0;
  52976. ActionManager._OnPickTrigger = 1;
  52977. ActionManager._OnLeftPickTrigger = 2;
  52978. ActionManager._OnRightPickTrigger = 3;
  52979. ActionManager._OnCenterPickTrigger = 4;
  52980. ActionManager._OnPickDownTrigger = 5;
  52981. ActionManager._OnDoublePickTrigger = 6;
  52982. ActionManager._OnPickUpTrigger = 7;
  52983. ActionManager._OnLongPressTrigger = 8;
  52984. ActionManager._OnPointerOverTrigger = 9;
  52985. ActionManager._OnPointerOutTrigger = 10;
  52986. ActionManager._OnEveryFrameTrigger = 11;
  52987. ActionManager._OnIntersectionEnterTrigger = 12;
  52988. ActionManager._OnIntersectionExitTrigger = 13;
  52989. ActionManager._OnKeyDownTrigger = 14;
  52990. ActionManager._OnKeyUpTrigger = 15;
  52991. ActionManager._OnPickOutTrigger = 16;
  52992. /** Gets the list of active triggers */
  52993. ActionManager.Triggers = {};
  52994. return ActionManager;
  52995. }());
  52996. BABYLON.ActionManager = ActionManager;
  52997. })(BABYLON || (BABYLON = {}));
  52998. //# sourceMappingURL=babylon.actionManager.js.map
  52999. var BABYLON;
  53000. (function (BABYLON) {
  53001. var InterpolateValueAction = /** @class */ (function (_super) {
  53002. __extends(InterpolateValueAction, _super);
  53003. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53004. if (duration === void 0) { duration = 1000; }
  53005. var _this = _super.call(this, triggerOptions, condition) || this;
  53006. _this.propertyPath = propertyPath;
  53007. _this.value = value;
  53008. _this.duration = duration;
  53009. _this.stopOtherAnimations = stopOtherAnimations;
  53010. _this.onInterpolationDone = onInterpolationDone;
  53011. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53012. _this._target = _this._effectiveTarget = target;
  53013. return _this;
  53014. }
  53015. InterpolateValueAction.prototype._prepare = function () {
  53016. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53017. this._property = this._getProperty(this.propertyPath);
  53018. };
  53019. InterpolateValueAction.prototype.execute = function () {
  53020. var _this = this;
  53021. var scene = this._actionManager.getScene();
  53022. var keys = [
  53023. {
  53024. frame: 0,
  53025. value: this._effectiveTarget[this._property]
  53026. }, {
  53027. frame: 100,
  53028. value: this.value
  53029. }
  53030. ];
  53031. var dataType;
  53032. if (typeof this.value === "number") {
  53033. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53034. }
  53035. else if (this.value instanceof BABYLON.Color3) {
  53036. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53037. }
  53038. else if (this.value instanceof BABYLON.Vector3) {
  53039. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53040. }
  53041. else if (this.value instanceof BABYLON.Matrix) {
  53042. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53043. }
  53044. else if (this.value instanceof BABYLON.Quaternion) {
  53045. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53046. }
  53047. else {
  53048. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53049. return;
  53050. }
  53051. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53052. animation.setKeys(keys);
  53053. if (this.stopOtherAnimations) {
  53054. scene.stopAnimation(this._effectiveTarget);
  53055. }
  53056. var wrapper = function () {
  53057. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53058. if (_this.onInterpolationDone) {
  53059. _this.onInterpolationDone();
  53060. }
  53061. };
  53062. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53063. };
  53064. InterpolateValueAction.prototype.serialize = function (parent) {
  53065. return _super.prototype._serialize.call(this, {
  53066. name: "InterpolateValueAction",
  53067. properties: [
  53068. BABYLON.Action._GetTargetProperty(this._target),
  53069. { name: "propertyPath", value: this.propertyPath },
  53070. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53071. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53072. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53073. ]
  53074. }, parent);
  53075. };
  53076. return InterpolateValueAction;
  53077. }(BABYLON.Action));
  53078. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53079. })(BABYLON || (BABYLON = {}));
  53080. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53081. var BABYLON;
  53082. (function (BABYLON) {
  53083. var SwitchBooleanAction = /** @class */ (function (_super) {
  53084. __extends(SwitchBooleanAction, _super);
  53085. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53086. var _this = _super.call(this, triggerOptions, condition) || this;
  53087. _this.propertyPath = propertyPath;
  53088. _this._target = _this._effectiveTarget = target;
  53089. return _this;
  53090. }
  53091. SwitchBooleanAction.prototype._prepare = function () {
  53092. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53093. this._property = this._getProperty(this.propertyPath);
  53094. };
  53095. SwitchBooleanAction.prototype.execute = function () {
  53096. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53097. };
  53098. SwitchBooleanAction.prototype.serialize = function (parent) {
  53099. return _super.prototype._serialize.call(this, {
  53100. name: "SwitchBooleanAction",
  53101. properties: [
  53102. BABYLON.Action._GetTargetProperty(this._target),
  53103. { name: "propertyPath", value: this.propertyPath }
  53104. ]
  53105. }, parent);
  53106. };
  53107. return SwitchBooleanAction;
  53108. }(BABYLON.Action));
  53109. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53110. var SetStateAction = /** @class */ (function (_super) {
  53111. __extends(SetStateAction, _super);
  53112. function SetStateAction(triggerOptions, target, value, condition) {
  53113. var _this = _super.call(this, triggerOptions, condition) || this;
  53114. _this.value = value;
  53115. _this._target = target;
  53116. return _this;
  53117. }
  53118. SetStateAction.prototype.execute = function () {
  53119. this._target.state = this.value;
  53120. };
  53121. SetStateAction.prototype.serialize = function (parent) {
  53122. return _super.prototype._serialize.call(this, {
  53123. name: "SetStateAction",
  53124. properties: [
  53125. BABYLON.Action._GetTargetProperty(this._target),
  53126. { name: "value", value: this.value }
  53127. ]
  53128. }, parent);
  53129. };
  53130. return SetStateAction;
  53131. }(BABYLON.Action));
  53132. BABYLON.SetStateAction = SetStateAction;
  53133. var SetValueAction = /** @class */ (function (_super) {
  53134. __extends(SetValueAction, _super);
  53135. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53136. var _this = _super.call(this, triggerOptions, condition) || this;
  53137. _this.propertyPath = propertyPath;
  53138. _this.value = value;
  53139. _this._target = _this._effectiveTarget = target;
  53140. return _this;
  53141. }
  53142. SetValueAction.prototype._prepare = function () {
  53143. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53144. this._property = this._getProperty(this.propertyPath);
  53145. };
  53146. SetValueAction.prototype.execute = function () {
  53147. this._effectiveTarget[this._property] = this.value;
  53148. if (this._target.markAsDirty) {
  53149. this._target.markAsDirty(this._property);
  53150. }
  53151. };
  53152. SetValueAction.prototype.serialize = function (parent) {
  53153. return _super.prototype._serialize.call(this, {
  53154. name: "SetValueAction",
  53155. properties: [
  53156. BABYLON.Action._GetTargetProperty(this._target),
  53157. { name: "propertyPath", value: this.propertyPath },
  53158. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53159. ]
  53160. }, parent);
  53161. };
  53162. return SetValueAction;
  53163. }(BABYLON.Action));
  53164. BABYLON.SetValueAction = SetValueAction;
  53165. var IncrementValueAction = /** @class */ (function (_super) {
  53166. __extends(IncrementValueAction, _super);
  53167. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53168. var _this = _super.call(this, triggerOptions, condition) || this;
  53169. _this.propertyPath = propertyPath;
  53170. _this.value = value;
  53171. _this._target = _this._effectiveTarget = target;
  53172. return _this;
  53173. }
  53174. IncrementValueAction.prototype._prepare = function () {
  53175. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53176. this._property = this._getProperty(this.propertyPath);
  53177. if (typeof this._effectiveTarget[this._property] !== "number") {
  53178. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53179. }
  53180. };
  53181. IncrementValueAction.prototype.execute = function () {
  53182. this._effectiveTarget[this._property] += this.value;
  53183. if (this._target.markAsDirty) {
  53184. this._target.markAsDirty(this._property);
  53185. }
  53186. };
  53187. IncrementValueAction.prototype.serialize = function (parent) {
  53188. return _super.prototype._serialize.call(this, {
  53189. name: "IncrementValueAction",
  53190. properties: [
  53191. BABYLON.Action._GetTargetProperty(this._target),
  53192. { name: "propertyPath", value: this.propertyPath },
  53193. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53194. ]
  53195. }, parent);
  53196. };
  53197. return IncrementValueAction;
  53198. }(BABYLON.Action));
  53199. BABYLON.IncrementValueAction = IncrementValueAction;
  53200. var PlayAnimationAction = /** @class */ (function (_super) {
  53201. __extends(PlayAnimationAction, _super);
  53202. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53203. var _this = _super.call(this, triggerOptions, condition) || this;
  53204. _this.from = from;
  53205. _this.to = to;
  53206. _this.loop = loop;
  53207. _this._target = target;
  53208. return _this;
  53209. }
  53210. PlayAnimationAction.prototype._prepare = function () {
  53211. };
  53212. PlayAnimationAction.prototype.execute = function () {
  53213. var scene = this._actionManager.getScene();
  53214. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53215. };
  53216. PlayAnimationAction.prototype.serialize = function (parent) {
  53217. return _super.prototype._serialize.call(this, {
  53218. name: "PlayAnimationAction",
  53219. properties: [
  53220. BABYLON.Action._GetTargetProperty(this._target),
  53221. { name: "from", value: String(this.from) },
  53222. { name: "to", value: String(this.to) },
  53223. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53224. ]
  53225. }, parent);
  53226. };
  53227. return PlayAnimationAction;
  53228. }(BABYLON.Action));
  53229. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53230. var StopAnimationAction = /** @class */ (function (_super) {
  53231. __extends(StopAnimationAction, _super);
  53232. function StopAnimationAction(triggerOptions, target, condition) {
  53233. var _this = _super.call(this, triggerOptions, condition) || this;
  53234. _this._target = target;
  53235. return _this;
  53236. }
  53237. StopAnimationAction.prototype._prepare = function () {
  53238. };
  53239. StopAnimationAction.prototype.execute = function () {
  53240. var scene = this._actionManager.getScene();
  53241. scene.stopAnimation(this._target);
  53242. };
  53243. StopAnimationAction.prototype.serialize = function (parent) {
  53244. return _super.prototype._serialize.call(this, {
  53245. name: "StopAnimationAction",
  53246. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53247. }, parent);
  53248. };
  53249. return StopAnimationAction;
  53250. }(BABYLON.Action));
  53251. BABYLON.StopAnimationAction = StopAnimationAction;
  53252. var DoNothingAction = /** @class */ (function (_super) {
  53253. __extends(DoNothingAction, _super);
  53254. function DoNothingAction(triggerOptions, condition) {
  53255. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53256. return _super.call(this, triggerOptions, condition) || this;
  53257. }
  53258. DoNothingAction.prototype.execute = function () {
  53259. };
  53260. DoNothingAction.prototype.serialize = function (parent) {
  53261. return _super.prototype._serialize.call(this, {
  53262. name: "DoNothingAction",
  53263. properties: []
  53264. }, parent);
  53265. };
  53266. return DoNothingAction;
  53267. }(BABYLON.Action));
  53268. BABYLON.DoNothingAction = DoNothingAction;
  53269. var CombineAction = /** @class */ (function (_super) {
  53270. __extends(CombineAction, _super);
  53271. function CombineAction(triggerOptions, children, condition) {
  53272. var _this = _super.call(this, triggerOptions, condition) || this;
  53273. _this.children = children;
  53274. return _this;
  53275. }
  53276. CombineAction.prototype._prepare = function () {
  53277. for (var index = 0; index < this.children.length; index++) {
  53278. this.children[index]._actionManager = this._actionManager;
  53279. this.children[index]._prepare();
  53280. }
  53281. };
  53282. CombineAction.prototype.execute = function (evt) {
  53283. for (var index = 0; index < this.children.length; index++) {
  53284. this.children[index].execute(evt);
  53285. }
  53286. };
  53287. CombineAction.prototype.serialize = function (parent) {
  53288. var serializationObject = _super.prototype._serialize.call(this, {
  53289. name: "CombineAction",
  53290. properties: [],
  53291. combine: []
  53292. }, parent);
  53293. for (var i = 0; i < this.children.length; i++) {
  53294. serializationObject.combine.push(this.children[i].serialize(null));
  53295. }
  53296. return serializationObject;
  53297. };
  53298. return CombineAction;
  53299. }(BABYLON.Action));
  53300. BABYLON.CombineAction = CombineAction;
  53301. var ExecuteCodeAction = /** @class */ (function (_super) {
  53302. __extends(ExecuteCodeAction, _super);
  53303. function ExecuteCodeAction(triggerOptions, func, condition) {
  53304. var _this = _super.call(this, triggerOptions, condition) || this;
  53305. _this.func = func;
  53306. return _this;
  53307. }
  53308. ExecuteCodeAction.prototype.execute = function (evt) {
  53309. this.func(evt);
  53310. };
  53311. return ExecuteCodeAction;
  53312. }(BABYLON.Action));
  53313. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53314. var SetParentAction = /** @class */ (function (_super) {
  53315. __extends(SetParentAction, _super);
  53316. function SetParentAction(triggerOptions, target, parent, condition) {
  53317. var _this = _super.call(this, triggerOptions, condition) || this;
  53318. _this._target = target;
  53319. _this._parent = parent;
  53320. return _this;
  53321. }
  53322. SetParentAction.prototype._prepare = function () {
  53323. };
  53324. SetParentAction.prototype.execute = function () {
  53325. if (this._target.parent === this._parent) {
  53326. return;
  53327. }
  53328. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53329. invertParentWorldMatrix.invert();
  53330. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53331. this._target.parent = this._parent;
  53332. };
  53333. SetParentAction.prototype.serialize = function (parent) {
  53334. return _super.prototype._serialize.call(this, {
  53335. name: "SetParentAction",
  53336. properties: [
  53337. BABYLON.Action._GetTargetProperty(this._target),
  53338. BABYLON.Action._GetTargetProperty(this._parent),
  53339. ]
  53340. }, parent);
  53341. };
  53342. return SetParentAction;
  53343. }(BABYLON.Action));
  53344. BABYLON.SetParentAction = SetParentAction;
  53345. var PlaySoundAction = /** @class */ (function (_super) {
  53346. __extends(PlaySoundAction, _super);
  53347. function PlaySoundAction(triggerOptions, sound, condition) {
  53348. var _this = _super.call(this, triggerOptions, condition) || this;
  53349. _this._sound = sound;
  53350. return _this;
  53351. }
  53352. PlaySoundAction.prototype._prepare = function () {
  53353. };
  53354. PlaySoundAction.prototype.execute = function () {
  53355. if (this._sound !== undefined)
  53356. this._sound.play();
  53357. };
  53358. PlaySoundAction.prototype.serialize = function (parent) {
  53359. return _super.prototype._serialize.call(this, {
  53360. name: "PlaySoundAction",
  53361. properties: [{ name: "sound", value: this._sound.name }]
  53362. }, parent);
  53363. };
  53364. return PlaySoundAction;
  53365. }(BABYLON.Action));
  53366. BABYLON.PlaySoundAction = PlaySoundAction;
  53367. var StopSoundAction = /** @class */ (function (_super) {
  53368. __extends(StopSoundAction, _super);
  53369. function StopSoundAction(triggerOptions, sound, condition) {
  53370. var _this = _super.call(this, triggerOptions, condition) || this;
  53371. _this._sound = sound;
  53372. return _this;
  53373. }
  53374. StopSoundAction.prototype._prepare = function () {
  53375. };
  53376. StopSoundAction.prototype.execute = function () {
  53377. if (this._sound !== undefined)
  53378. this._sound.stop();
  53379. };
  53380. StopSoundAction.prototype.serialize = function (parent) {
  53381. return _super.prototype._serialize.call(this, {
  53382. name: "StopSoundAction",
  53383. properties: [{ name: "sound", value: this._sound.name }]
  53384. }, parent);
  53385. };
  53386. return StopSoundAction;
  53387. }(BABYLON.Action));
  53388. BABYLON.StopSoundAction = StopSoundAction;
  53389. })(BABYLON || (BABYLON = {}));
  53390. //# sourceMappingURL=babylon.directActions.js.map
  53391. var BABYLON;
  53392. (function (BABYLON) {
  53393. var SpriteManager = /** @class */ (function () {
  53394. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53395. if (epsilon === void 0) { epsilon = 0.01; }
  53396. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53397. this.name = name;
  53398. this.sprites = new Array();
  53399. this.renderingGroupId = 0;
  53400. this.layerMask = 0x0FFFFFFF;
  53401. this.fogEnabled = true;
  53402. this.isPickable = false;
  53403. /**
  53404. * An event triggered when the manager is disposed.
  53405. */
  53406. this.onDisposeObservable = new BABYLON.Observable();
  53407. this._vertexBuffers = {};
  53408. this._capacity = capacity;
  53409. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53410. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53411. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53412. if (cellSize.width && cellSize.height) {
  53413. this.cellWidth = cellSize.width;
  53414. this.cellHeight = cellSize.height;
  53415. }
  53416. else if (cellSize !== undefined) {
  53417. this.cellWidth = cellSize;
  53418. this.cellHeight = cellSize;
  53419. }
  53420. else {
  53421. return;
  53422. }
  53423. this._epsilon = epsilon;
  53424. this._scene = scene;
  53425. this._scene.spriteManagers.push(this);
  53426. var indices = [];
  53427. var index = 0;
  53428. for (var count = 0; count < capacity; count++) {
  53429. indices.push(index);
  53430. indices.push(index + 1);
  53431. indices.push(index + 2);
  53432. indices.push(index);
  53433. indices.push(index + 2);
  53434. indices.push(index + 3);
  53435. index += 4;
  53436. }
  53437. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53438. // VBO
  53439. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53440. this._vertexData = new Float32Array(capacity * 16 * 4);
  53441. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53442. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53443. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53444. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53445. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53446. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53447. this._vertexBuffers["options"] = options;
  53448. this._vertexBuffers["cellInfo"] = cellInfo;
  53449. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53450. // Effects
  53451. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53452. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53453. }
  53454. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53455. set: function (callback) {
  53456. if (this._onDisposeObserver) {
  53457. this.onDisposeObservable.remove(this._onDisposeObserver);
  53458. }
  53459. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53460. },
  53461. enumerable: true,
  53462. configurable: true
  53463. });
  53464. Object.defineProperty(SpriteManager.prototype, "texture", {
  53465. get: function () {
  53466. return this._spriteTexture;
  53467. },
  53468. set: function (value) {
  53469. this._spriteTexture = value;
  53470. },
  53471. enumerable: true,
  53472. configurable: true
  53473. });
  53474. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53475. var arrayOffset = index * 16;
  53476. if (offsetX === 0)
  53477. offsetX = this._epsilon;
  53478. else if (offsetX === 1)
  53479. offsetX = 1 - this._epsilon;
  53480. if (offsetY === 0)
  53481. offsetY = this._epsilon;
  53482. else if (offsetY === 1)
  53483. offsetY = 1 - this._epsilon;
  53484. this._vertexData[arrayOffset] = sprite.position.x;
  53485. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53486. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53487. this._vertexData[arrayOffset + 3] = sprite.angle;
  53488. this._vertexData[arrayOffset + 4] = sprite.width;
  53489. this._vertexData[arrayOffset + 5] = sprite.height;
  53490. this._vertexData[arrayOffset + 6] = offsetX;
  53491. this._vertexData[arrayOffset + 7] = offsetY;
  53492. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53493. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53494. var offset = (sprite.cellIndex / rowSize) >> 0;
  53495. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53496. this._vertexData[arrayOffset + 11] = offset;
  53497. // Color
  53498. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53499. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53500. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53501. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53502. };
  53503. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53504. var count = Math.min(this._capacity, this.sprites.length);
  53505. var min = BABYLON.Vector3.Zero();
  53506. var max = BABYLON.Vector3.Zero();
  53507. var distance = Number.MAX_VALUE;
  53508. var currentSprite = null;
  53509. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53510. var cameraView = camera.getViewMatrix();
  53511. for (var index = 0; index < count; index++) {
  53512. var sprite = this.sprites[index];
  53513. if (!sprite) {
  53514. continue;
  53515. }
  53516. if (predicate) {
  53517. if (!predicate(sprite)) {
  53518. continue;
  53519. }
  53520. }
  53521. else if (!sprite.isPickable) {
  53522. continue;
  53523. }
  53524. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53525. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53526. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53527. if (ray.intersectsBoxMinMax(min, max)) {
  53528. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53529. if (distance > currentDistance) {
  53530. distance = currentDistance;
  53531. currentSprite = sprite;
  53532. if (fastCheck) {
  53533. break;
  53534. }
  53535. }
  53536. }
  53537. }
  53538. if (currentSprite) {
  53539. var result = new BABYLON.PickingInfo();
  53540. result.hit = true;
  53541. result.pickedSprite = currentSprite;
  53542. result.distance = distance;
  53543. return result;
  53544. }
  53545. return null;
  53546. };
  53547. SpriteManager.prototype.render = function () {
  53548. // Check
  53549. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53550. return;
  53551. var engine = this._scene.getEngine();
  53552. var baseSize = this._spriteTexture.getBaseSize();
  53553. // Sprites
  53554. var deltaTime = engine.getDeltaTime();
  53555. var max = Math.min(this._capacity, this.sprites.length);
  53556. var rowSize = baseSize.width / this.cellWidth;
  53557. var offset = 0;
  53558. for (var index = 0; index < max; index++) {
  53559. var sprite = this.sprites[index];
  53560. if (!sprite || !sprite.isVisible) {
  53561. continue;
  53562. }
  53563. sprite._animate(deltaTime);
  53564. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53565. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53566. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53567. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53568. }
  53569. this._buffer.update(this._vertexData);
  53570. // Render
  53571. var effect = this._effectBase;
  53572. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53573. effect = this._effectFog;
  53574. }
  53575. engine.enableEffect(effect);
  53576. var viewMatrix = this._scene.getViewMatrix();
  53577. effect.setTexture("diffuseSampler", this._spriteTexture);
  53578. effect.setMatrix("view", viewMatrix);
  53579. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53580. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53581. // Fog
  53582. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53583. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53584. effect.setColor3("vFogColor", this._scene.fogColor);
  53585. }
  53586. // VBOs
  53587. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53588. // Draw order
  53589. engine.setDepthFunctionToLessOrEqual();
  53590. effect.setBool("alphaTest", true);
  53591. engine.setColorWrite(false);
  53592. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53593. engine.setColorWrite(true);
  53594. effect.setBool("alphaTest", false);
  53595. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53596. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53597. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53598. };
  53599. SpriteManager.prototype.dispose = function () {
  53600. if (this._buffer) {
  53601. this._buffer.dispose();
  53602. this._buffer = null;
  53603. }
  53604. if (this._indexBuffer) {
  53605. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53606. this._indexBuffer = null;
  53607. }
  53608. if (this._spriteTexture) {
  53609. this._spriteTexture.dispose();
  53610. this._spriteTexture = null;
  53611. }
  53612. // Remove from scene
  53613. var index = this._scene.spriteManagers.indexOf(this);
  53614. this._scene.spriteManagers.splice(index, 1);
  53615. // Callback
  53616. this.onDisposeObservable.notifyObservers(this);
  53617. this.onDisposeObservable.clear();
  53618. };
  53619. return SpriteManager;
  53620. }());
  53621. BABYLON.SpriteManager = SpriteManager;
  53622. })(BABYLON || (BABYLON = {}));
  53623. //# sourceMappingURL=babylon.spriteManager.js.map
  53624. var BABYLON;
  53625. (function (BABYLON) {
  53626. var Sprite = /** @class */ (function () {
  53627. function Sprite(name, manager) {
  53628. this.name = name;
  53629. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53630. this.width = 1.0;
  53631. this.height = 1.0;
  53632. this.angle = 0;
  53633. this.cellIndex = 0;
  53634. this.invertU = 0;
  53635. this.invertV = 0;
  53636. this.animations = new Array();
  53637. this.isPickable = false;
  53638. this._animationStarted = false;
  53639. this._loopAnimation = false;
  53640. this._fromIndex = 0;
  53641. this._toIndex = 0;
  53642. this._delay = 0;
  53643. this._direction = 1;
  53644. this._time = 0;
  53645. /**
  53646. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53647. */
  53648. this.isVisible = true;
  53649. this._manager = manager;
  53650. this._manager.sprites.push(this);
  53651. this.position = BABYLON.Vector3.Zero();
  53652. }
  53653. Object.defineProperty(Sprite.prototype, "size", {
  53654. get: function () {
  53655. return this.width;
  53656. },
  53657. set: function (value) {
  53658. this.width = value;
  53659. this.height = value;
  53660. },
  53661. enumerable: true,
  53662. configurable: true
  53663. });
  53664. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53665. this._fromIndex = from;
  53666. this._toIndex = to;
  53667. this._loopAnimation = loop;
  53668. this._delay = delay;
  53669. this._animationStarted = true;
  53670. this._direction = from < to ? 1 : -1;
  53671. this.cellIndex = from;
  53672. this._time = 0;
  53673. this._onAnimationEnd = onAnimationEnd;
  53674. };
  53675. Sprite.prototype.stopAnimation = function () {
  53676. this._animationStarted = false;
  53677. };
  53678. Sprite.prototype._animate = function (deltaTime) {
  53679. if (!this._animationStarted)
  53680. return;
  53681. this._time += deltaTime;
  53682. if (this._time > this._delay) {
  53683. this._time = this._time % this._delay;
  53684. this.cellIndex += this._direction;
  53685. if (this.cellIndex > this._toIndex) {
  53686. if (this._loopAnimation) {
  53687. this.cellIndex = this._fromIndex;
  53688. }
  53689. else {
  53690. this.cellIndex = this._toIndex;
  53691. this._animationStarted = false;
  53692. if (this._onAnimationEnd) {
  53693. this._onAnimationEnd();
  53694. }
  53695. if (this.disposeWhenFinishedAnimating) {
  53696. this.dispose();
  53697. }
  53698. }
  53699. }
  53700. }
  53701. };
  53702. Sprite.prototype.dispose = function () {
  53703. for (var i = 0; i < this._manager.sprites.length; i++) {
  53704. if (this._manager.sprites[i] == this) {
  53705. this._manager.sprites.splice(i, 1);
  53706. }
  53707. }
  53708. };
  53709. return Sprite;
  53710. }());
  53711. BABYLON.Sprite = Sprite;
  53712. })(BABYLON || (BABYLON = {}));
  53713. //# sourceMappingURL=babylon.sprite.js.map
  53714. var BABYLON;
  53715. (function (BABYLON) {
  53716. var IntersectionInfo = /** @class */ (function () {
  53717. function IntersectionInfo(bu, bv, distance) {
  53718. this.bu = bu;
  53719. this.bv = bv;
  53720. this.distance = distance;
  53721. this.faceId = 0;
  53722. this.subMeshId = 0;
  53723. }
  53724. return IntersectionInfo;
  53725. }());
  53726. BABYLON.IntersectionInfo = IntersectionInfo;
  53727. /**
  53728. * Information about the result of picking within a scene
  53729. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53730. */
  53731. var PickingInfo = /** @class */ (function () {
  53732. function PickingInfo() {
  53733. /**
  53734. * If the pick collided with an object
  53735. */
  53736. this.hit = false;
  53737. /**
  53738. * Distance away where the pick collided
  53739. */
  53740. this.distance = 0;
  53741. /**
  53742. * The location of pick collision
  53743. */
  53744. this.pickedPoint = null;
  53745. /**
  53746. * The mesh corrisponding the the pick collision
  53747. */
  53748. this.pickedMesh = null;
  53749. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53750. this.bu = 0;
  53751. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53752. this.bv = 0;
  53753. /** The id of the face on the mesh that was picked */
  53754. this.faceId = -1;
  53755. /** Id of the the submesh that was picked */
  53756. this.subMeshId = 0;
  53757. /** If a sprite was picked, this will be the sprite the pick collided with */
  53758. this.pickedSprite = null;
  53759. /**
  53760. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53761. */
  53762. this.originMesh = null;
  53763. /**
  53764. * The ray that was used to perform the picking.
  53765. */
  53766. this.ray = null;
  53767. }
  53768. /**
  53769. * Gets the normal corrispodning to the face the pick collided with
  53770. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53771. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53772. * @returns The normal corrispodning to the face the pick collided with
  53773. */
  53774. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53775. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53776. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53777. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53778. return null;
  53779. }
  53780. var indices = this.pickedMesh.getIndices();
  53781. if (!indices) {
  53782. return null;
  53783. }
  53784. var result;
  53785. if (useVerticesNormals) {
  53786. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53787. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53788. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53789. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53790. normal0 = normal0.scale(this.bu);
  53791. normal1 = normal1.scale(this.bv);
  53792. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53793. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53794. }
  53795. else {
  53796. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53797. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53798. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53799. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53800. var p1p2 = vertex1.subtract(vertex2);
  53801. var p3p2 = vertex3.subtract(vertex2);
  53802. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53803. }
  53804. if (useWorldCoordinates) {
  53805. var wm = this.pickedMesh.getWorldMatrix();
  53806. if (this.pickedMesh.nonUniformScaling) {
  53807. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53808. wm = BABYLON.Tmp.Matrix[0];
  53809. wm.setTranslationFromFloats(0, 0, 0);
  53810. wm.invert();
  53811. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53812. wm = BABYLON.Tmp.Matrix[1];
  53813. }
  53814. result = BABYLON.Vector3.TransformNormal(result, wm);
  53815. }
  53816. result.normalize();
  53817. return result;
  53818. };
  53819. /**
  53820. * Gets the texture coordinates of where the pick occured
  53821. * @returns the vector containing the coordnates of the texture
  53822. */
  53823. PickingInfo.prototype.getTextureCoordinates = function () {
  53824. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53825. return null;
  53826. }
  53827. var indices = this.pickedMesh.getIndices();
  53828. if (!indices) {
  53829. return null;
  53830. }
  53831. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53832. if (!uvs) {
  53833. return null;
  53834. }
  53835. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53836. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53837. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53838. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53839. uv1 = uv1.scale(this.bu);
  53840. uv2 = uv2.scale(this.bv);
  53841. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53842. };
  53843. return PickingInfo;
  53844. }());
  53845. BABYLON.PickingInfo = PickingInfo;
  53846. })(BABYLON || (BABYLON = {}));
  53847. //# sourceMappingURL=babylon.pickingInfo.js.map
  53848. var BABYLON;
  53849. (function (BABYLON) {
  53850. var Ray = /** @class */ (function () {
  53851. function Ray(origin, direction, length) {
  53852. if (length === void 0) { length = Number.MAX_VALUE; }
  53853. this.origin = origin;
  53854. this.direction = direction;
  53855. this.length = length;
  53856. }
  53857. // Methods
  53858. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53859. var d = 0.0;
  53860. var maxValue = Number.MAX_VALUE;
  53861. var inv;
  53862. var min;
  53863. var max;
  53864. var temp;
  53865. if (Math.abs(this.direction.x) < 0.0000001) {
  53866. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53867. return false;
  53868. }
  53869. }
  53870. else {
  53871. inv = 1.0 / this.direction.x;
  53872. min = (minimum.x - this.origin.x) * inv;
  53873. max = (maximum.x - this.origin.x) * inv;
  53874. if (max === -Infinity) {
  53875. max = Infinity;
  53876. }
  53877. if (min > max) {
  53878. temp = min;
  53879. min = max;
  53880. max = temp;
  53881. }
  53882. d = Math.max(min, d);
  53883. maxValue = Math.min(max, maxValue);
  53884. if (d > maxValue) {
  53885. return false;
  53886. }
  53887. }
  53888. if (Math.abs(this.direction.y) < 0.0000001) {
  53889. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53890. return false;
  53891. }
  53892. }
  53893. else {
  53894. inv = 1.0 / this.direction.y;
  53895. min = (minimum.y - this.origin.y) * inv;
  53896. max = (maximum.y - this.origin.y) * inv;
  53897. if (max === -Infinity) {
  53898. max = Infinity;
  53899. }
  53900. if (min > max) {
  53901. temp = min;
  53902. min = max;
  53903. max = temp;
  53904. }
  53905. d = Math.max(min, d);
  53906. maxValue = Math.min(max, maxValue);
  53907. if (d > maxValue) {
  53908. return false;
  53909. }
  53910. }
  53911. if (Math.abs(this.direction.z) < 0.0000001) {
  53912. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53913. return false;
  53914. }
  53915. }
  53916. else {
  53917. inv = 1.0 / this.direction.z;
  53918. min = (minimum.z - this.origin.z) * inv;
  53919. max = (maximum.z - this.origin.z) * inv;
  53920. if (max === -Infinity) {
  53921. max = Infinity;
  53922. }
  53923. if (min > max) {
  53924. temp = min;
  53925. min = max;
  53926. max = temp;
  53927. }
  53928. d = Math.max(min, d);
  53929. maxValue = Math.min(max, maxValue);
  53930. if (d > maxValue) {
  53931. return false;
  53932. }
  53933. }
  53934. return true;
  53935. };
  53936. Ray.prototype.intersectsBox = function (box) {
  53937. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53938. };
  53939. Ray.prototype.intersectsSphere = function (sphere) {
  53940. var x = sphere.center.x - this.origin.x;
  53941. var y = sphere.center.y - this.origin.y;
  53942. var z = sphere.center.z - this.origin.z;
  53943. var pyth = (x * x) + (y * y) + (z * z);
  53944. var rr = sphere.radius * sphere.radius;
  53945. if (pyth <= rr) {
  53946. return true;
  53947. }
  53948. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53949. if (dot < 0.0) {
  53950. return false;
  53951. }
  53952. var temp = pyth - (dot * dot);
  53953. return temp <= rr;
  53954. };
  53955. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53956. if (!this._edge1) {
  53957. this._edge1 = BABYLON.Vector3.Zero();
  53958. this._edge2 = BABYLON.Vector3.Zero();
  53959. this._pvec = BABYLON.Vector3.Zero();
  53960. this._tvec = BABYLON.Vector3.Zero();
  53961. this._qvec = BABYLON.Vector3.Zero();
  53962. }
  53963. vertex1.subtractToRef(vertex0, this._edge1);
  53964. vertex2.subtractToRef(vertex0, this._edge2);
  53965. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53966. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53967. if (det === 0) {
  53968. return null;
  53969. }
  53970. var invdet = 1 / det;
  53971. this.origin.subtractToRef(vertex0, this._tvec);
  53972. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53973. if (bu < 0 || bu > 1.0) {
  53974. return null;
  53975. }
  53976. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53977. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53978. if (bv < 0 || bu + bv > 1.0) {
  53979. return null;
  53980. }
  53981. //check if the distance is longer than the predefined length.
  53982. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53983. if (distance > this.length) {
  53984. return null;
  53985. }
  53986. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53987. };
  53988. Ray.prototype.intersectsPlane = function (plane) {
  53989. var distance;
  53990. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53991. if (Math.abs(result1) < 9.99999997475243E-07) {
  53992. return null;
  53993. }
  53994. else {
  53995. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53996. distance = (-plane.d - result2) / result1;
  53997. if (distance < 0.0) {
  53998. if (distance < -9.99999997475243E-07) {
  53999. return null;
  54000. }
  54001. else {
  54002. return 0;
  54003. }
  54004. }
  54005. return distance;
  54006. }
  54007. };
  54008. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54009. var tm = BABYLON.Tmp.Matrix[0];
  54010. mesh.getWorldMatrix().invertToRef(tm);
  54011. if (this._tmpRay) {
  54012. Ray.TransformToRef(this, tm, this._tmpRay);
  54013. }
  54014. else {
  54015. this._tmpRay = Ray.Transform(this, tm);
  54016. }
  54017. return mesh.intersects(this._tmpRay, fastCheck);
  54018. };
  54019. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54020. if (results) {
  54021. results.length = 0;
  54022. }
  54023. else {
  54024. results = [];
  54025. }
  54026. for (var i = 0; i < meshes.length; i++) {
  54027. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54028. if (pickInfo.hit) {
  54029. results.push(pickInfo);
  54030. }
  54031. }
  54032. results.sort(this._comparePickingInfo);
  54033. return results;
  54034. };
  54035. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54036. if (pickingInfoA.distance < pickingInfoB.distance) {
  54037. return -1;
  54038. }
  54039. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54040. return 1;
  54041. }
  54042. else {
  54043. return 0;
  54044. }
  54045. };
  54046. /**
  54047. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54048. * @param sega the first point of the segment to test the intersection against
  54049. * @param segb the second point of the segment to test the intersection against
  54050. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54051. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54052. */
  54053. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54054. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54055. var u = segb.subtract(sega);
  54056. var v = rsegb.subtract(this.origin);
  54057. var w = sega.subtract(this.origin);
  54058. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54059. var b = BABYLON.Vector3.Dot(u, v);
  54060. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54061. var d = BABYLON.Vector3.Dot(u, w);
  54062. var e = BABYLON.Vector3.Dot(v, w);
  54063. var D = a * c - b * b; // always >= 0
  54064. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54065. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54066. // compute the line parameters of the two closest points
  54067. if (D < Ray.smallnum) { // the lines are almost parallel
  54068. sN = 0.0; // force using point P0 on segment S1
  54069. sD = 1.0; // to prevent possible division by 0.0 later
  54070. tN = e;
  54071. tD = c;
  54072. }
  54073. else { // get the closest points on the infinite lines
  54074. sN = (b * e - c * d);
  54075. tN = (a * e - b * d);
  54076. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54077. sN = 0.0;
  54078. tN = e;
  54079. tD = c;
  54080. }
  54081. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54082. sN = sD;
  54083. tN = e + b;
  54084. tD = c;
  54085. }
  54086. }
  54087. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54088. tN = 0.0;
  54089. // recompute sc for this edge
  54090. if (-d < 0.0) {
  54091. sN = 0.0;
  54092. }
  54093. else if (-d > a)
  54094. sN = sD;
  54095. else {
  54096. sN = -d;
  54097. sD = a;
  54098. }
  54099. }
  54100. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54101. tN = tD;
  54102. // recompute sc for this edge
  54103. if ((-d + b) < 0.0) {
  54104. sN = 0;
  54105. }
  54106. else if ((-d + b) > a) {
  54107. sN = sD;
  54108. }
  54109. else {
  54110. sN = (-d + b);
  54111. sD = a;
  54112. }
  54113. }
  54114. // finally do the division to get sc and tc
  54115. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54116. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54117. // get the difference of the two closest points
  54118. var qtc = v.multiplyByFloats(tc, tc, tc);
  54119. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54120. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54121. if (isIntersected) {
  54122. return qtc.length();
  54123. }
  54124. return -1;
  54125. };
  54126. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54127. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54128. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54129. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54130. this.direction.normalize();
  54131. return this;
  54132. };
  54133. // Statics
  54134. Ray.Zero = function () {
  54135. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54136. };
  54137. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54138. var result = Ray.Zero();
  54139. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54140. };
  54141. /**
  54142. * 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
  54143. * transformed to the given world matrix.
  54144. * @param origin The origin point
  54145. * @param end The end point
  54146. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54147. */
  54148. Ray.CreateNewFromTo = function (origin, end, world) {
  54149. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54150. var direction = end.subtract(origin);
  54151. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54152. direction.normalize();
  54153. return Ray.Transform(new Ray(origin, direction, length), world);
  54154. };
  54155. Ray.Transform = function (ray, matrix) {
  54156. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54157. Ray.TransformToRef(ray, matrix, result);
  54158. return result;
  54159. };
  54160. Ray.TransformToRef = function (ray, matrix, result) {
  54161. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54162. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54163. result.length = ray.length;
  54164. var dir = result.direction;
  54165. var len = dir.length();
  54166. if (!(len === 0 || len === 1)) {
  54167. var num = 1.0 / len;
  54168. dir.x *= num;
  54169. dir.y *= num;
  54170. dir.z *= num;
  54171. result.length *= len;
  54172. }
  54173. };
  54174. Ray.smallnum = 0.00000001;
  54175. Ray.rayl = 10e8;
  54176. return Ray;
  54177. }());
  54178. BABYLON.Ray = Ray;
  54179. })(BABYLON || (BABYLON = {}));
  54180. //# sourceMappingURL=babylon.ray.js.map
  54181. var BABYLON;
  54182. (function (BABYLON) {
  54183. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54184. if (boxMin.x > sphereCenter.x + sphereRadius)
  54185. return false;
  54186. if (sphereCenter.x - sphereRadius > boxMax.x)
  54187. return false;
  54188. if (boxMin.y > sphereCenter.y + sphereRadius)
  54189. return false;
  54190. if (sphereCenter.y - sphereRadius > boxMax.y)
  54191. return false;
  54192. if (boxMin.z > sphereCenter.z + sphereRadius)
  54193. return false;
  54194. if (sphereCenter.z - sphereRadius > boxMax.z)
  54195. return false;
  54196. return true;
  54197. };
  54198. var getLowestRoot = (function () {
  54199. var result = { root: 0, found: false };
  54200. return function (a, b, c, maxR) {
  54201. result.root = 0;
  54202. result.found = false;
  54203. var determinant = b * b - 4.0 * a * c;
  54204. if (determinant < 0)
  54205. return result;
  54206. var sqrtD = Math.sqrt(determinant);
  54207. var r1 = (-b - sqrtD) / (2.0 * a);
  54208. var r2 = (-b + sqrtD) / (2.0 * a);
  54209. if (r1 > r2) {
  54210. var temp = r2;
  54211. r2 = r1;
  54212. r1 = temp;
  54213. }
  54214. if (r1 > 0 && r1 < maxR) {
  54215. result.root = r1;
  54216. result.found = true;
  54217. return result;
  54218. }
  54219. if (r2 > 0 && r2 < maxR) {
  54220. result.root = r2;
  54221. result.found = true;
  54222. return result;
  54223. }
  54224. return result;
  54225. };
  54226. })();
  54227. var Collider = /** @class */ (function () {
  54228. function Collider() {
  54229. this._collisionPoint = BABYLON.Vector3.Zero();
  54230. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54231. this._tempVector = BABYLON.Vector3.Zero();
  54232. this._tempVector2 = BABYLON.Vector3.Zero();
  54233. this._tempVector3 = BABYLON.Vector3.Zero();
  54234. this._tempVector4 = BABYLON.Vector3.Zero();
  54235. this._edge = BABYLON.Vector3.Zero();
  54236. this._baseToVertex = BABYLON.Vector3.Zero();
  54237. this._destinationPoint = BABYLON.Vector3.Zero();
  54238. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54239. this._displacementVector = BABYLON.Vector3.Zero();
  54240. this._radius = BABYLON.Vector3.One();
  54241. this._retry = 0;
  54242. this._basePointWorld = BABYLON.Vector3.Zero();
  54243. this._velocityWorld = BABYLON.Vector3.Zero();
  54244. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54245. this._collisionMask = -1;
  54246. }
  54247. Object.defineProperty(Collider.prototype, "collisionMask", {
  54248. get: function () {
  54249. return this._collisionMask;
  54250. },
  54251. set: function (mask) {
  54252. this._collisionMask = !isNaN(mask) ? mask : -1;
  54253. },
  54254. enumerable: true,
  54255. configurable: true
  54256. });
  54257. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54258. /**
  54259. * Gets the plane normal used to compute the sliding response (in local space)
  54260. */
  54261. get: function () {
  54262. return this._slidePlaneNormal;
  54263. },
  54264. enumerable: true,
  54265. configurable: true
  54266. });
  54267. // Methods
  54268. Collider.prototype._initialize = function (source, dir, e) {
  54269. this._velocity = dir;
  54270. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54271. this._basePoint = source;
  54272. source.multiplyToRef(this._radius, this._basePointWorld);
  54273. dir.multiplyToRef(this._radius, this._velocityWorld);
  54274. this._velocityWorldLength = this._velocityWorld.length();
  54275. this._epsilon = e;
  54276. this.collisionFound = false;
  54277. };
  54278. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54279. pa.subtractToRef(point, this._tempVector);
  54280. pb.subtractToRef(point, this._tempVector2);
  54281. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54282. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54283. if (d < 0)
  54284. return false;
  54285. pc.subtractToRef(point, this._tempVector3);
  54286. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54287. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54288. if (d < 0)
  54289. return false;
  54290. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54291. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54292. return d >= 0;
  54293. };
  54294. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54295. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54296. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54297. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54298. return false;
  54299. }
  54300. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54301. return false;
  54302. return true;
  54303. };
  54304. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54305. var t0;
  54306. var embeddedInPlane = false;
  54307. //defensive programming, actually not needed.
  54308. if (!trianglePlaneArray) {
  54309. trianglePlaneArray = [];
  54310. }
  54311. if (!trianglePlaneArray[faceIndex]) {
  54312. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54313. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54314. }
  54315. var trianglePlane = trianglePlaneArray[faceIndex];
  54316. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54317. return;
  54318. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54319. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54320. if (normalDotVelocity == 0) {
  54321. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54322. return;
  54323. embeddedInPlane = true;
  54324. t0 = 0;
  54325. }
  54326. else {
  54327. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54328. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54329. if (t0 > t1) {
  54330. var temp = t1;
  54331. t1 = t0;
  54332. t0 = temp;
  54333. }
  54334. if (t0 > 1.0 || t1 < 0.0)
  54335. return;
  54336. if (t0 < 0)
  54337. t0 = 0;
  54338. if (t0 > 1.0)
  54339. t0 = 1.0;
  54340. }
  54341. this._collisionPoint.copyFromFloats(0, 0, 0);
  54342. var found = false;
  54343. var t = 1.0;
  54344. if (!embeddedInPlane) {
  54345. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54346. this._velocity.scaleToRef(t0, this._tempVector);
  54347. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54348. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54349. found = true;
  54350. t = t0;
  54351. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54352. }
  54353. }
  54354. if (!found) {
  54355. var velocitySquaredLength = this._velocity.lengthSquared();
  54356. var a = velocitySquaredLength;
  54357. this._basePoint.subtractToRef(p1, this._tempVector);
  54358. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54359. var c = this._tempVector.lengthSquared() - 1.0;
  54360. var lowestRoot = getLowestRoot(a, b, c, t);
  54361. if (lowestRoot.found) {
  54362. t = lowestRoot.root;
  54363. found = true;
  54364. this._collisionPoint.copyFrom(p1);
  54365. }
  54366. this._basePoint.subtractToRef(p2, this._tempVector);
  54367. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54368. c = this._tempVector.lengthSquared() - 1.0;
  54369. lowestRoot = getLowestRoot(a, b, c, t);
  54370. if (lowestRoot.found) {
  54371. t = lowestRoot.root;
  54372. found = true;
  54373. this._collisionPoint.copyFrom(p2);
  54374. }
  54375. this._basePoint.subtractToRef(p3, this._tempVector);
  54376. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54377. c = this._tempVector.lengthSquared() - 1.0;
  54378. lowestRoot = getLowestRoot(a, b, c, t);
  54379. if (lowestRoot.found) {
  54380. t = lowestRoot.root;
  54381. found = true;
  54382. this._collisionPoint.copyFrom(p3);
  54383. }
  54384. p2.subtractToRef(p1, this._edge);
  54385. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54386. var edgeSquaredLength = this._edge.lengthSquared();
  54387. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54388. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54389. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54390. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54391. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54392. lowestRoot = getLowestRoot(a, b, c, t);
  54393. if (lowestRoot.found) {
  54394. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54395. if (f >= 0.0 && f <= 1.0) {
  54396. t = lowestRoot.root;
  54397. found = true;
  54398. this._edge.scaleInPlace(f);
  54399. p1.addToRef(this._edge, this._collisionPoint);
  54400. }
  54401. }
  54402. p3.subtractToRef(p2, this._edge);
  54403. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54404. edgeSquaredLength = this._edge.lengthSquared();
  54405. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54406. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54407. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54408. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54409. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54410. lowestRoot = getLowestRoot(a, b, c, t);
  54411. if (lowestRoot.found) {
  54412. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54413. if (f >= 0.0 && f <= 1.0) {
  54414. t = lowestRoot.root;
  54415. found = true;
  54416. this._edge.scaleInPlace(f);
  54417. p2.addToRef(this._edge, this._collisionPoint);
  54418. }
  54419. }
  54420. p1.subtractToRef(p3, this._edge);
  54421. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54422. edgeSquaredLength = this._edge.lengthSquared();
  54423. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54424. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54425. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54426. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54427. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54428. lowestRoot = getLowestRoot(a, b, c, t);
  54429. if (lowestRoot.found) {
  54430. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54431. if (f >= 0.0 && f <= 1.0) {
  54432. t = lowestRoot.root;
  54433. found = true;
  54434. this._edge.scaleInPlace(f);
  54435. p3.addToRef(this._edge, this._collisionPoint);
  54436. }
  54437. }
  54438. }
  54439. if (found) {
  54440. var distToCollision = t * this._velocity.length();
  54441. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54442. if (!this.intersectionPoint) {
  54443. this.intersectionPoint = this._collisionPoint.clone();
  54444. }
  54445. else {
  54446. this.intersectionPoint.copyFrom(this._collisionPoint);
  54447. }
  54448. this._nearestDistance = distToCollision;
  54449. this.collisionFound = true;
  54450. }
  54451. }
  54452. };
  54453. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54454. for (var i = indexStart; i < indexEnd; i += 3) {
  54455. var p1 = pts[indices[i] - decal];
  54456. var p2 = pts[indices[i + 1] - decal];
  54457. var p3 = pts[indices[i + 2] - decal];
  54458. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54459. }
  54460. };
  54461. Collider.prototype._getResponse = function (pos, vel) {
  54462. pos.addToRef(vel, this._destinationPoint);
  54463. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54464. this._basePoint.addToRef(vel, pos);
  54465. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54466. this._slidePlaneNormal.normalize();
  54467. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54468. pos.addInPlace(this._displacementVector);
  54469. this.intersectionPoint.addInPlace(this._displacementVector);
  54470. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54471. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54472. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54473. };
  54474. return Collider;
  54475. }());
  54476. BABYLON.Collider = Collider;
  54477. })(BABYLON || (BABYLON = {}));
  54478. //# sourceMappingURL=babylon.collider.js.map
  54479. var BABYLON;
  54480. (function (BABYLON) {
  54481. //WebWorker code will be inserted to this variable.
  54482. BABYLON.CollisionWorker = "";
  54483. /** Defines supported task for worker process */
  54484. var WorkerTaskType;
  54485. (function (WorkerTaskType) {
  54486. /** Initialization */
  54487. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54488. /** Update of geometry */
  54489. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54490. /** Evaluate collision */
  54491. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54492. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54493. /** Defines kind of replies returned by worker */
  54494. var WorkerReplyType;
  54495. (function (WorkerReplyType) {
  54496. /** Success */
  54497. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54498. /** Unkown error */
  54499. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54500. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54501. var CollisionCoordinatorWorker = /** @class */ (function () {
  54502. function CollisionCoordinatorWorker() {
  54503. var _this = this;
  54504. this._scaledPosition = BABYLON.Vector3.Zero();
  54505. this._scaledVelocity = BABYLON.Vector3.Zero();
  54506. this.onMeshUpdated = function (transformNode) {
  54507. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54508. };
  54509. this.onGeometryUpdated = function (geometry) {
  54510. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54511. };
  54512. this._afterRender = function () {
  54513. if (!_this._init)
  54514. return;
  54515. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54516. return;
  54517. }
  54518. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54519. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54520. if (_this._runningUpdated > 4) {
  54521. return;
  54522. }
  54523. ++_this._runningUpdated;
  54524. var payload = {
  54525. updatedMeshes: _this._addUpdateMeshesList,
  54526. updatedGeometries: _this._addUpdateGeometriesList,
  54527. removedGeometries: _this._toRemoveGeometryArray,
  54528. removedMeshes: _this._toRemoveMeshesArray
  54529. };
  54530. var message = {
  54531. payload: payload,
  54532. taskType: WorkerTaskType.UPDATE
  54533. };
  54534. var serializable = [];
  54535. for (var id in payload.updatedGeometries) {
  54536. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54537. //prepare transferables
  54538. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54539. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54540. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54541. }
  54542. }
  54543. _this._worker.postMessage(message, serializable);
  54544. _this._addUpdateMeshesList = {};
  54545. _this._addUpdateGeometriesList = {};
  54546. _this._toRemoveGeometryArray = [];
  54547. _this._toRemoveMeshesArray = [];
  54548. };
  54549. this._onMessageFromWorker = function (e) {
  54550. var returnData = e.data;
  54551. if (returnData.error != WorkerReplyType.SUCCESS) {
  54552. //TODO what errors can be returned from the worker?
  54553. BABYLON.Tools.Warn("error returned from worker!");
  54554. return;
  54555. }
  54556. switch (returnData.taskType) {
  54557. case WorkerTaskType.INIT:
  54558. _this._init = true;
  54559. //Update the worked with ALL of the scene's current state
  54560. _this._scene.meshes.forEach(function (mesh) {
  54561. _this.onMeshAdded(mesh);
  54562. });
  54563. _this._scene.getGeometries().forEach(function (geometry) {
  54564. _this.onGeometryAdded(geometry);
  54565. });
  54566. break;
  54567. case WorkerTaskType.UPDATE:
  54568. _this._runningUpdated--;
  54569. break;
  54570. case WorkerTaskType.COLLIDE:
  54571. var returnPayload = returnData.payload;
  54572. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54573. return;
  54574. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54575. if (callback) {
  54576. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54577. if (mesh) {
  54578. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54579. }
  54580. }
  54581. //cleanup
  54582. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54583. break;
  54584. }
  54585. };
  54586. this._collisionsCallbackArray = [];
  54587. this._init = false;
  54588. this._runningUpdated = 0;
  54589. this._addUpdateMeshesList = {};
  54590. this._addUpdateGeometriesList = {};
  54591. this._toRemoveGeometryArray = [];
  54592. this._toRemoveMeshesArray = [];
  54593. }
  54594. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54595. if (!this._init)
  54596. return;
  54597. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54598. return;
  54599. position.divideToRef(collider._radius, this._scaledPosition);
  54600. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54601. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54602. var payload = {
  54603. collider: {
  54604. position: this._scaledPosition.asArray(),
  54605. velocity: this._scaledVelocity.asArray(),
  54606. radius: collider._radius.asArray()
  54607. },
  54608. collisionId: collisionIndex,
  54609. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54610. maximumRetry: maximumRetry
  54611. };
  54612. var message = {
  54613. payload: payload,
  54614. taskType: WorkerTaskType.COLLIDE
  54615. };
  54616. this._worker.postMessage(message);
  54617. };
  54618. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54619. this._scene = scene;
  54620. this._scene.registerAfterRender(this._afterRender);
  54621. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54622. this._worker = new Worker(workerUrl);
  54623. this._worker.onmessage = this._onMessageFromWorker;
  54624. var message = {
  54625. payload: {},
  54626. taskType: WorkerTaskType.INIT
  54627. };
  54628. this._worker.postMessage(message);
  54629. };
  54630. CollisionCoordinatorWorker.prototype.destroy = function () {
  54631. this._scene.unregisterAfterRender(this._afterRender);
  54632. this._worker.terminate();
  54633. };
  54634. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54635. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54636. this.onMeshUpdated(mesh);
  54637. };
  54638. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54639. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54640. };
  54641. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54642. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54643. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54644. this.onGeometryUpdated(geometry);
  54645. };
  54646. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54647. this._toRemoveGeometryArray.push(geometry.id);
  54648. };
  54649. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54650. var submeshes = [];
  54651. if (mesh.subMeshes) {
  54652. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54653. var boundingInfo = sm.getBoundingInfo();
  54654. return {
  54655. position: idx,
  54656. verticesStart: sm.verticesStart,
  54657. verticesCount: sm.verticesCount,
  54658. indexStart: sm.indexStart,
  54659. indexCount: sm.indexCount,
  54660. hasMaterial: !!sm.getMaterial(),
  54661. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54662. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54663. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54664. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54665. };
  54666. });
  54667. }
  54668. var geometryId = null;
  54669. if (mesh instanceof BABYLON.Mesh) {
  54670. var geometry = mesh.geometry;
  54671. geometryId = geometry ? geometry.id : null;
  54672. }
  54673. else if (mesh instanceof BABYLON.InstancedMesh) {
  54674. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54675. geometryId = geometry ? geometry.id : null;
  54676. }
  54677. var boundingInfo = mesh.getBoundingInfo();
  54678. return {
  54679. uniqueId: mesh.uniqueId,
  54680. id: mesh.id,
  54681. name: mesh.name,
  54682. geometryId: geometryId,
  54683. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54684. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54685. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54686. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54687. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54688. subMeshes: submeshes,
  54689. checkCollisions: mesh.checkCollisions
  54690. };
  54691. };
  54692. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54693. return {
  54694. id: geometry.id,
  54695. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54696. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54697. indices: new Uint32Array(geometry.getIndices() || []),
  54698. };
  54699. };
  54700. return CollisionCoordinatorWorker;
  54701. }());
  54702. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54703. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54704. function CollisionCoordinatorLegacy() {
  54705. this._scaledPosition = BABYLON.Vector3.Zero();
  54706. this._scaledVelocity = BABYLON.Vector3.Zero();
  54707. this._finalPosition = BABYLON.Vector3.Zero();
  54708. }
  54709. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54710. position.divideToRef(collider._radius, this._scaledPosition);
  54711. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54712. collider.collidedMesh = null;
  54713. collider._retry = 0;
  54714. collider._initialVelocity = this._scaledVelocity;
  54715. collider._initialPosition = this._scaledPosition;
  54716. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54717. this._finalPosition.multiplyInPlace(collider._radius);
  54718. //run the callback
  54719. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54720. };
  54721. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54722. this._scene = scene;
  54723. };
  54724. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54725. //Legacy need no destruction method.
  54726. };
  54727. //No update in legacy mode
  54728. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54729. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54730. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54731. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54732. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54733. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54734. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54735. if (excludedMesh === void 0) { excludedMesh = null; }
  54736. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54737. if (collider._retry >= maximumRetry) {
  54738. finalPosition.copyFrom(position);
  54739. return;
  54740. }
  54741. // Check if this is a mesh else camera or -1
  54742. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54743. collider._initialize(position, velocity, closeDistance);
  54744. // Check all meshes
  54745. for (var index = 0; index < this._scene.meshes.length; index++) {
  54746. var mesh = this._scene.meshes[index];
  54747. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54748. mesh._checkCollision(collider);
  54749. }
  54750. }
  54751. if (!collider.collisionFound) {
  54752. position.addToRef(velocity, finalPosition);
  54753. return;
  54754. }
  54755. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54756. collider._getResponse(position, velocity);
  54757. }
  54758. if (velocity.length() <= closeDistance) {
  54759. finalPosition.copyFrom(position);
  54760. return;
  54761. }
  54762. collider._retry++;
  54763. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54764. };
  54765. return CollisionCoordinatorLegacy;
  54766. }());
  54767. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54768. })(BABYLON || (BABYLON = {}));
  54769. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54770. var BABYLON;
  54771. (function (BABYLON) {
  54772. /**
  54773. * A particle represents one of the element emitted by a particle system.
  54774. * This is mainly define by its coordinates, direction, velocity and age.
  54775. */
  54776. var Particle = /** @class */ (function () {
  54777. /**
  54778. * Creates a new instance Particle
  54779. * @param particleSystem the particle system the particle belongs to
  54780. */
  54781. function Particle(
  54782. /**
  54783. * particleSystem the particle system the particle belongs to.
  54784. */
  54785. particleSystem) {
  54786. this.particleSystem = particleSystem;
  54787. /**
  54788. * The world position of the particle in the scene.
  54789. */
  54790. this.position = BABYLON.Vector3.Zero();
  54791. /**
  54792. * The world direction of the particle in the scene.
  54793. */
  54794. this.direction = BABYLON.Vector3.Zero();
  54795. /**
  54796. * The color of the particle.
  54797. */
  54798. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54799. /**
  54800. * The color change of the particle per step.
  54801. */
  54802. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54803. /**
  54804. * Defines how long will the life of the particle be.
  54805. */
  54806. this.lifeTime = 1.0;
  54807. /**
  54808. * The current age of the particle.
  54809. */
  54810. this.age = 0;
  54811. /**
  54812. * The current size of the particle.
  54813. */
  54814. this.size = 0;
  54815. /**
  54816. * The current scale of the particle.
  54817. */
  54818. this.scale = new BABYLON.Vector2(1, 1);
  54819. /**
  54820. * The current angle of the particle.
  54821. */
  54822. this.angle = 0;
  54823. /**
  54824. * Defines how fast is the angle changing.
  54825. */
  54826. this.angularSpeed = 0;
  54827. /**
  54828. * Defines the cell index used by the particle to be rendered from a sprite.
  54829. */
  54830. this.cellIndex = 0;
  54831. /** @hidden */
  54832. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54833. /** @hidden */
  54834. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54835. /** @hidden */
  54836. this._currentSize1 = 0;
  54837. /** @hidden */
  54838. this._currentSize2 = 0;
  54839. /** @hidden */
  54840. this._currentAngularSpeed1 = 0;
  54841. /** @hidden */
  54842. this._currentAngularSpeed2 = 0;
  54843. /** @hidden */
  54844. this._currentVelocity1 = 0;
  54845. /** @hidden */
  54846. this._currentVelocity2 = 0;
  54847. if (!this.particleSystem.isAnimationSheetEnabled) {
  54848. return;
  54849. }
  54850. this.updateCellInfoFromSystem();
  54851. }
  54852. Particle.prototype.updateCellInfoFromSystem = function () {
  54853. this.cellIndex = this.particleSystem.startSpriteCellID;
  54854. };
  54855. /**
  54856. * Defines how the sprite cell index is updated for the particle
  54857. */
  54858. Particle.prototype.updateCellIndex = function () {
  54859. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54860. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54861. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54862. };
  54863. /**
  54864. * Copy the properties of particle to another one.
  54865. * @param other the particle to copy the information to.
  54866. */
  54867. Particle.prototype.copyTo = function (other) {
  54868. other.position.copyFrom(this.position);
  54869. if (this._initialDirection) {
  54870. if (other._initialDirection) {
  54871. other._initialDirection.copyFrom(this._initialDirection);
  54872. }
  54873. else {
  54874. other._initialDirection = this._initialDirection.clone();
  54875. }
  54876. }
  54877. else {
  54878. other._initialDirection = null;
  54879. }
  54880. other.direction.copyFrom(this.direction);
  54881. other.color.copyFrom(this.color);
  54882. other.colorStep.copyFrom(this.colorStep);
  54883. other.lifeTime = this.lifeTime;
  54884. other.age = this.age;
  54885. other.size = this.size;
  54886. other.scale.copyFrom(this.scale);
  54887. other.angle = this.angle;
  54888. other.angularSpeed = this.angularSpeed;
  54889. other.particleSystem = this.particleSystem;
  54890. other.cellIndex = this.cellIndex;
  54891. if (this._currentColorGradient) {
  54892. other._currentColorGradient = this._currentColorGradient;
  54893. other._currentColor1.copyFrom(this._currentColor1);
  54894. other._currentColor2.copyFrom(this._currentColor2);
  54895. }
  54896. if (this._currentSizeGradient) {
  54897. other._currentSizeGradient = this._currentSizeGradient;
  54898. other._currentSize1 = this._currentSize1;
  54899. other._currentSize2 = this._currentSize2;
  54900. }
  54901. if (this._currentAngularSpeedGradient) {
  54902. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54903. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54904. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54905. }
  54906. if (this._currentVelocityGradient) {
  54907. other._currentVelocityGradient = this._currentVelocityGradient;
  54908. other._currentVelocity1 = this._currentVelocity1;
  54909. other._currentVelocity2 = this._currentVelocity2;
  54910. }
  54911. if (this.particleSystem.isAnimationSheetEnabled) {
  54912. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54913. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54914. }
  54915. };
  54916. return Particle;
  54917. }());
  54918. BABYLON.Particle = Particle;
  54919. })(BABYLON || (BABYLON = {}));
  54920. //# sourceMappingURL=babylon.particle.js.map
  54921. var BABYLON;
  54922. (function (BABYLON) {
  54923. /**
  54924. * This represents a particle system in Babylon.
  54925. * 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.
  54926. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54927. * @example https://doc.babylonjs.com/babylon101/particles
  54928. */
  54929. var ParticleSystem = /** @class */ (function () {
  54930. /**
  54931. * Instantiates a particle system.
  54932. * 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.
  54933. * @param name The name of the particle system
  54934. * @param capacity The max number of particles alive at the same time
  54935. * @param scene The scene the particle system belongs to
  54936. * @param customEffect a custom effect used to change the way particles are rendered by default
  54937. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54938. * @param epsilon Offset used to render the particles
  54939. */
  54940. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54941. if (customEffect === void 0) { customEffect = null; }
  54942. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54943. if (epsilon === void 0) { epsilon = 0.01; }
  54944. var _this = this;
  54945. /**
  54946. * List of animations used by the particle system.
  54947. */
  54948. this.animations = [];
  54949. /**
  54950. * The rendering group used by the Particle system to chose when to render.
  54951. */
  54952. this.renderingGroupId = 0;
  54953. /**
  54954. * The emitter represents the Mesh or position we are attaching the particle system to.
  54955. */
  54956. this.emitter = null;
  54957. /**
  54958. * The maximum number of particles to emit per frame
  54959. */
  54960. this.emitRate = 10;
  54961. /**
  54962. * If you want to launch only a few particles at once, that can be done, as well.
  54963. */
  54964. this.manualEmitCount = -1;
  54965. /**
  54966. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54967. */
  54968. this.updateSpeed = 0.01;
  54969. /**
  54970. * The amount of time the particle system is running (depends of the overall update speed).
  54971. */
  54972. this.targetStopDuration = 0;
  54973. /**
  54974. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54975. */
  54976. this.disposeOnStop = false;
  54977. /**
  54978. * Minimum power of emitting particles.
  54979. */
  54980. this.minEmitPower = 1;
  54981. /**
  54982. * Maximum power of emitting particles.
  54983. */
  54984. this.maxEmitPower = 1;
  54985. /**
  54986. * Minimum life time of emitting particles.
  54987. */
  54988. this.minLifeTime = 1;
  54989. /**
  54990. * Maximum life time of emitting particles.
  54991. */
  54992. this.maxLifeTime = 1;
  54993. /**
  54994. * Minimum Size of emitting particles.
  54995. */
  54996. this.minSize = 1;
  54997. /**
  54998. * Maximum Size of emitting particles.
  54999. */
  55000. this.maxSize = 1;
  55001. /**
  55002. * Minimum scale of emitting particles on X axis.
  55003. */
  55004. this.minScaleX = 1;
  55005. /**
  55006. * Maximum scale of emitting particles on X axis.
  55007. */
  55008. this.maxScaleX = 1;
  55009. /**
  55010. * Minimum scale of emitting particles on Y axis.
  55011. */
  55012. this.minScaleY = 1;
  55013. /**
  55014. * Maximum scale of emitting particles on Y axis.
  55015. */
  55016. this.maxScaleY = 1;
  55017. /**
  55018. * Gets or sets the minimal initial rotation in radians.
  55019. */
  55020. this.minInitialRotation = 0;
  55021. /**
  55022. * Gets or sets the maximal initial rotation in radians.
  55023. */
  55024. this.maxInitialRotation = 0;
  55025. /**
  55026. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55027. */
  55028. this.minAngularSpeed = 0;
  55029. /**
  55030. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55031. */
  55032. this.maxAngularSpeed = 0;
  55033. /**
  55034. * The layer mask we are rendering the particles through.
  55035. */
  55036. this.layerMask = 0x0FFFFFFF;
  55037. /**
  55038. * This can help using your own shader to render the particle system.
  55039. * The according effect will be created
  55040. */
  55041. this.customShader = null;
  55042. /**
  55043. * By default particle system starts as soon as they are created. This prevents the
  55044. * automatic start to happen and let you decide when to start emitting particles.
  55045. */
  55046. this.preventAutoStart = false;
  55047. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55048. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55049. /**
  55050. * Callback triggered when the particle animation is ending.
  55051. */
  55052. this.onAnimationEnd = null;
  55053. /**
  55054. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55055. */
  55056. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55057. /**
  55058. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55059. * to override the particles.
  55060. */
  55061. this.forceDepthWrite = false;
  55062. /**
  55063. * You can use gravity if you want to give an orientation to your particles.
  55064. */
  55065. this.gravity = BABYLON.Vector3.Zero();
  55066. this._colorGradients = null;
  55067. this._sizeGradients = null;
  55068. this._lifeTimeGradients = null;
  55069. this._angularSpeedGradients = null;
  55070. this._velocityGradients = null;
  55071. /**
  55072. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55073. */
  55074. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55075. /**
  55076. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55077. */
  55078. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55079. /**
  55080. * Color the particle will have at the end of its lifetime
  55081. */
  55082. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55083. /**
  55084. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55085. */
  55086. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55087. /**
  55088. * 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)
  55089. */
  55090. this.spriteCellChangeSpeed = 1;
  55091. /**
  55092. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55093. */
  55094. this.startSpriteCellID = 0;
  55095. /**
  55096. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55097. */
  55098. this.endSpriteCellID = 0;
  55099. /**
  55100. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55101. */
  55102. this.spriteCellWidth = 0;
  55103. /**
  55104. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55105. */
  55106. this.spriteCellHeight = 0;
  55107. /** 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 */
  55108. this.preWarmCycles = 0;
  55109. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55110. this.preWarmStepOffset = 1;
  55111. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55112. this.translationPivot = new BABYLON.Vector2(0, 0);
  55113. /**
  55114. * An event triggered when the system is disposed
  55115. */
  55116. this.onDisposeObservable = new BABYLON.Observable();
  55117. /**
  55118. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55119. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55120. */
  55121. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55122. this._particles = new Array();
  55123. this._stockParticles = new Array();
  55124. this._newPartsExcess = 0;
  55125. this._vertexBuffers = {};
  55126. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55127. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55128. this._scaledDirection = BABYLON.Vector3.Zero();
  55129. this._scaledGravity = BABYLON.Vector3.Zero();
  55130. this._currentRenderId = -1;
  55131. this._useInstancing = false;
  55132. this._started = false;
  55133. this._stopped = false;
  55134. this._actualFrame = 0;
  55135. this._isBillboardBased = true;
  55136. // start of sub system methods
  55137. /**
  55138. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55139. * Its lifetime will start back at 0.
  55140. */
  55141. this.recycleParticle = function (particle) {
  55142. var lastParticle = _this._particles.pop();
  55143. if (lastParticle !== particle) {
  55144. lastParticle.copyTo(particle);
  55145. }
  55146. _this._stockParticles.push(lastParticle);
  55147. };
  55148. this._createParticle = function () {
  55149. var particle;
  55150. if (_this._stockParticles.length !== 0) {
  55151. particle = _this._stockParticles.pop();
  55152. particle.age = 0;
  55153. particle._currentColorGradient = null;
  55154. particle.cellIndex = _this.startSpriteCellID;
  55155. }
  55156. else {
  55157. particle = new BABYLON.Particle(_this);
  55158. }
  55159. return particle;
  55160. };
  55161. this._emitFromParticle = function (particle) {
  55162. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55163. return;
  55164. }
  55165. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55166. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55167. subSystem._rootParticleSystem = _this;
  55168. _this.activeSubSystems.push(subSystem);
  55169. subSystem.start();
  55170. };
  55171. this.id = name;
  55172. this.name = name;
  55173. this._capacity = capacity;
  55174. this._epsilon = epsilon;
  55175. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55176. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55177. this._customEffect = customEffect;
  55178. this._scene.particleSystems.push(this);
  55179. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55180. this._createIndexBuffer();
  55181. this._createVertexBuffers();
  55182. // Default emitter type
  55183. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55184. this.updateFunction = function (particles) {
  55185. var noiseTextureData = null;
  55186. var noiseTextureSize = null;
  55187. if (_this.noiseTexture) { // We need to get texture data back to CPU
  55188. noiseTextureData = (_this.noiseTexture.readPixels());
  55189. noiseTextureSize = _this.noiseTexture.getSize();
  55190. }
  55191. var _loop_1 = function () {
  55192. particle = particles[index];
  55193. particle.age += _this._scaledUpdateSpeed;
  55194. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55195. _this._emitFromParticle(particle);
  55196. _this.recycleParticle(particle);
  55197. index--;
  55198. return "continue";
  55199. }
  55200. else {
  55201. var ratio = particle.age / particle.lifeTime;
  55202. // Color
  55203. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55204. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55205. if (currentGradient !== particle._currentColorGradient) {
  55206. particle._currentColor1.copyFrom(particle._currentColor2);
  55207. nextGradient.getColorToRef(particle._currentColor2);
  55208. particle._currentColorGradient = currentGradient;
  55209. }
  55210. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55211. });
  55212. }
  55213. else {
  55214. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55215. particle.color.addInPlace(_this._scaledColorStep);
  55216. if (particle.color.a < 0) {
  55217. particle.color.a = 0;
  55218. }
  55219. }
  55220. // Angular speed
  55221. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55222. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55223. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55224. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55225. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55226. particle._currentAngularSpeedGradient = currentGradient;
  55227. }
  55228. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55229. });
  55230. }
  55231. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55232. // Direction
  55233. var directionScale_1 = _this._scaledUpdateSpeed;
  55234. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55235. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55236. if (currentGradient !== particle._currentVelocityGradient) {
  55237. particle._currentVelocity1 = particle._currentVelocity2;
  55238. particle._currentVelocity2 = nextGradient.getFactor();
  55239. particle._currentVelocityGradient = currentGradient;
  55240. }
  55241. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55242. });
  55243. }
  55244. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55245. particle.position.addInPlace(_this._scaledDirection);
  55246. // Noise
  55247. if (noiseTextureData && noiseTextureSize) {
  55248. var localPosition = BABYLON.Tmp.Vector3[0];
  55249. var emitterPosition = BABYLON.Tmp.Vector3[1];
  55250. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  55251. particle.position.subtractToRef(emitterPosition, localPosition);
  55252. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55253. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55254. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55255. var force = BABYLON.Tmp.Vector3[0];
  55256. var scaledForce = BABYLON.Tmp.Vector3[1];
  55257. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  55258. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  55259. particle.direction.addInPlace(scaledForce);
  55260. }
  55261. // Gravity
  55262. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55263. particle.direction.addInPlace(_this._scaledGravity);
  55264. // Size
  55265. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55266. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55267. if (currentGradient !== particle._currentSizeGradient) {
  55268. particle._currentSize1 = particle._currentSize2;
  55269. particle._currentSize2 = nextGradient.getFactor();
  55270. particle._currentSizeGradient = currentGradient;
  55271. }
  55272. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55273. });
  55274. }
  55275. if (_this._isAnimationSheetEnabled) {
  55276. particle.updateCellIndex();
  55277. }
  55278. }
  55279. };
  55280. var particle;
  55281. for (var index = 0; index < particles.length; index++) {
  55282. _loop_1();
  55283. }
  55284. };
  55285. }
  55286. /**
  55287. * Gets the current list of color gradients.
  55288. * You must use addColorGradient and removeColorGradient to udpate this list
  55289. * @returns the list of color gradients
  55290. */
  55291. ParticleSystem.prototype.getColorGradients = function () {
  55292. return this._colorGradients;
  55293. };
  55294. /**
  55295. * Gets the current list of size gradients.
  55296. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55297. * @returns the list of size gradients
  55298. */
  55299. ParticleSystem.prototype.getSizeGradients = function () {
  55300. return this._sizeGradients;
  55301. };
  55302. /**
  55303. * Gets the current list of life time gradients.
  55304. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55305. * @returns the list of life time gradients
  55306. */
  55307. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55308. return this._lifeTimeGradients;
  55309. };
  55310. /**
  55311. * Gets the current list of angular speed gradients.
  55312. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55313. * @returns the list of angular speed gradients
  55314. */
  55315. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55316. return this._angularSpeedGradients;
  55317. };
  55318. /**
  55319. * Gets the current list of velocity gradients.
  55320. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55321. * @returns the list of velocity gradients
  55322. */
  55323. ParticleSystem.prototype.getVelocityGradients = function () {
  55324. return this._velocityGradients;
  55325. };
  55326. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55327. /**
  55328. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55329. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55330. */
  55331. get: function () {
  55332. if (this.particleEmitterType.direction1) {
  55333. return this.particleEmitterType.direction1;
  55334. }
  55335. return BABYLON.Vector3.Zero();
  55336. },
  55337. set: function (value) {
  55338. if (this.particleEmitterType.direction1) {
  55339. this.particleEmitterType.direction1 = value;
  55340. }
  55341. },
  55342. enumerable: true,
  55343. configurable: true
  55344. });
  55345. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55346. /**
  55347. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55348. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55349. */
  55350. get: function () {
  55351. if (this.particleEmitterType.direction2) {
  55352. return this.particleEmitterType.direction2;
  55353. }
  55354. return BABYLON.Vector3.Zero();
  55355. },
  55356. set: function (value) {
  55357. if (this.particleEmitterType.direction2) {
  55358. this.particleEmitterType.direction2 = value;
  55359. }
  55360. },
  55361. enumerable: true,
  55362. configurable: true
  55363. });
  55364. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55365. /**
  55366. * 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.
  55367. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55368. */
  55369. get: function () {
  55370. if (this.particleEmitterType.minEmitBox) {
  55371. return this.particleEmitterType.minEmitBox;
  55372. }
  55373. return BABYLON.Vector3.Zero();
  55374. },
  55375. set: function (value) {
  55376. if (this.particleEmitterType.minEmitBox) {
  55377. this.particleEmitterType.minEmitBox = value;
  55378. }
  55379. },
  55380. enumerable: true,
  55381. configurable: true
  55382. });
  55383. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55384. /**
  55385. * 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.
  55386. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55387. */
  55388. get: function () {
  55389. if (this.particleEmitterType.maxEmitBox) {
  55390. return this.particleEmitterType.maxEmitBox;
  55391. }
  55392. return BABYLON.Vector3.Zero();
  55393. },
  55394. set: function (value) {
  55395. if (this.particleEmitterType.maxEmitBox) {
  55396. this.particleEmitterType.maxEmitBox = value;
  55397. }
  55398. },
  55399. enumerable: true,
  55400. configurable: true
  55401. });
  55402. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55403. /**
  55404. * Sets a callback that will be triggered when the system is disposed
  55405. */
  55406. set: function (callback) {
  55407. if (this._onDisposeObserver) {
  55408. this.onDisposeObservable.remove(this._onDisposeObserver);
  55409. }
  55410. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55411. },
  55412. enumerable: true,
  55413. configurable: true
  55414. });
  55415. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55416. /**
  55417. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55418. */
  55419. get: function () {
  55420. return this._isAnimationSheetEnabled;
  55421. },
  55422. set: function (value) {
  55423. if (this._isAnimationSheetEnabled == value) {
  55424. return;
  55425. }
  55426. this._isAnimationSheetEnabled = value;
  55427. this._resetEffect();
  55428. },
  55429. enumerable: true,
  55430. configurable: true
  55431. });
  55432. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55433. /**
  55434. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55435. */
  55436. get: function () {
  55437. return this._isBillboardBased;
  55438. },
  55439. set: function (value) {
  55440. if (this._isBillboardBased === value) {
  55441. return;
  55442. }
  55443. this._isBillboardBased = value;
  55444. this._resetEffect();
  55445. },
  55446. enumerable: true,
  55447. configurable: true
  55448. });
  55449. /**
  55450. * Get hosting scene
  55451. * @returns the scene
  55452. */
  55453. ParticleSystem.prototype.getScene = function () {
  55454. return this._scene;
  55455. };
  55456. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55457. //end of Sub-emitter
  55458. /**
  55459. * Gets the current list of active particles
  55460. */
  55461. get: function () {
  55462. return this._particles;
  55463. },
  55464. enumerable: true,
  55465. configurable: true
  55466. });
  55467. /**
  55468. * Returns the string "ParticleSystem"
  55469. * @returns a string containing the class name
  55470. */
  55471. ParticleSystem.prototype.getClassName = function () {
  55472. return "ParticleSystem";
  55473. };
  55474. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  55475. u = Math.abs(u) * 0.5 + 0.5;
  55476. v = Math.abs(v) * 0.5 + 0.5;
  55477. var wrappedU = ((u * width) % width) | 0;
  55478. var wrappedV = ((v * height) % height) | 0;
  55479. var position = (wrappedU + wrappedV * width) * 4;
  55480. return pixels[position] / 255;
  55481. };
  55482. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55483. var newGradient = new BABYLON.FactorGradient();
  55484. newGradient.gradient = gradient;
  55485. newGradient.factor1 = factor;
  55486. newGradient.factor2 = factor2;
  55487. factorGradients.push(newGradient);
  55488. factorGradients.sort(function (a, b) {
  55489. if (a.gradient < b.gradient) {
  55490. return -1;
  55491. }
  55492. else if (a.gradient > b.gradient) {
  55493. return 1;
  55494. }
  55495. return 0;
  55496. });
  55497. };
  55498. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55499. if (!factorGradients) {
  55500. return;
  55501. }
  55502. var index = 0;
  55503. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55504. var factorGradient = factorGradients_1[_i];
  55505. if (factorGradient.gradient === gradient) {
  55506. factorGradients.splice(index, 1);
  55507. break;
  55508. }
  55509. index++;
  55510. }
  55511. };
  55512. /**
  55513. * Adds a new life time gradient
  55514. * @param gradient defines the gradient to use (between 0 and 1)
  55515. * @param factor defines the life time factor to affect to the specified gradient
  55516. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55517. * @returns the current particle system
  55518. */
  55519. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55520. if (!this._lifeTimeGradients) {
  55521. this._lifeTimeGradients = [];
  55522. }
  55523. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55524. return this;
  55525. };
  55526. /**
  55527. * Remove a specific life time gradient
  55528. * @param gradient defines the gradient to remove
  55529. * @returns the current particle system
  55530. */
  55531. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55532. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55533. return this;
  55534. };
  55535. /**
  55536. * Adds a new size gradient
  55537. * @param gradient defines the gradient to use (between 0 and 1)
  55538. * @param factor defines the size factor to affect to the specified gradient
  55539. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55540. * @returns the current particle system
  55541. */
  55542. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55543. if (!this._sizeGradients) {
  55544. this._sizeGradients = [];
  55545. }
  55546. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55547. return this;
  55548. };
  55549. /**
  55550. * Remove a specific size gradient
  55551. * @param gradient defines the gradient to remove
  55552. * @returns the current particle system
  55553. */
  55554. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55555. this._removeFactorGradient(this._sizeGradients, gradient);
  55556. return this;
  55557. };
  55558. /**
  55559. * Adds a new angular speed gradient
  55560. * @param gradient defines the gradient to use (between 0 and 1)
  55561. * @param factor defines the size factor to affect to the specified gradient
  55562. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55563. * @returns the current particle system
  55564. */
  55565. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55566. if (!this._angularSpeedGradients) {
  55567. this._angularSpeedGradients = [];
  55568. }
  55569. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55570. return this;
  55571. };
  55572. /**
  55573. * Remove a specific angular speed gradient
  55574. * @param gradient defines the gradient to remove
  55575. * @returns the current particle system
  55576. */
  55577. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55578. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55579. return this;
  55580. };
  55581. /**
  55582. * Adds a new velocity gradient
  55583. * @param gradient defines the gradient to use (between 0 and 1)
  55584. * @param factor defines the size factor to affect to the specified gradient
  55585. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55586. * @returns the current particle system
  55587. */
  55588. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55589. if (!this._velocityGradients) {
  55590. this._velocityGradients = [];
  55591. }
  55592. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55593. return this;
  55594. };
  55595. /**
  55596. * Remove a specific velocity gradient
  55597. * @param gradient defines the gradient to remove
  55598. * @returns the current particle system
  55599. */
  55600. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55601. this._removeFactorGradient(this._velocityGradients, gradient);
  55602. return this;
  55603. };
  55604. /**
  55605. * Adds a new color gradient
  55606. * @param gradient defines the gradient to use (between 0 and 1)
  55607. * @param color defines the color to affect to the specified gradient
  55608. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55609. */
  55610. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55611. if (!this._colorGradients) {
  55612. this._colorGradients = [];
  55613. }
  55614. var colorGradient = new BABYLON.ColorGradient();
  55615. colorGradient.gradient = gradient;
  55616. colorGradient.color1 = color;
  55617. colorGradient.color2 = color2;
  55618. this._colorGradients.push(colorGradient);
  55619. this._colorGradients.sort(function (a, b) {
  55620. if (a.gradient < b.gradient) {
  55621. return -1;
  55622. }
  55623. else if (a.gradient > b.gradient) {
  55624. return 1;
  55625. }
  55626. return 0;
  55627. });
  55628. return this;
  55629. };
  55630. /**
  55631. * Remove a specific color gradient
  55632. * @param gradient defines the gradient to remove
  55633. */
  55634. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55635. if (!this._colorGradients) {
  55636. return this;
  55637. }
  55638. var index = 0;
  55639. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55640. var colorGradient = _a[_i];
  55641. if (colorGradient.gradient === gradient) {
  55642. this._colorGradients.splice(index, 1);
  55643. break;
  55644. }
  55645. index++;
  55646. }
  55647. return this;
  55648. };
  55649. ParticleSystem.prototype._resetEffect = function () {
  55650. if (this._vertexBuffer) {
  55651. this._vertexBuffer.dispose();
  55652. this._vertexBuffer = null;
  55653. }
  55654. if (this._spriteBuffer) {
  55655. this._spriteBuffer.dispose();
  55656. this._spriteBuffer = null;
  55657. }
  55658. this._createVertexBuffers();
  55659. };
  55660. ParticleSystem.prototype._createVertexBuffers = function () {
  55661. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55662. if (this._isAnimationSheetEnabled) {
  55663. this._vertexBufferSize += 1;
  55664. }
  55665. if (!this._isBillboardBased) {
  55666. this._vertexBufferSize += 3;
  55667. }
  55668. var engine = this._scene.getEngine();
  55669. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55670. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55671. var dataOffset = 0;
  55672. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55673. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55674. dataOffset += 3;
  55675. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55676. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55677. dataOffset += 4;
  55678. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55679. this._vertexBuffers["angle"] = options;
  55680. dataOffset += 1;
  55681. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55682. this._vertexBuffers["size"] = size;
  55683. dataOffset += 2;
  55684. if (this._isAnimationSheetEnabled) {
  55685. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55686. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55687. dataOffset += 1;
  55688. }
  55689. if (!this._isBillboardBased) {
  55690. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55691. this._vertexBuffers["direction"] = directionBuffer;
  55692. dataOffset += 3;
  55693. }
  55694. var offsets;
  55695. if (this._useInstancing) {
  55696. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55697. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55698. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55699. }
  55700. else {
  55701. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55702. dataOffset += 2;
  55703. }
  55704. this._vertexBuffers["offset"] = offsets;
  55705. };
  55706. ParticleSystem.prototype._createIndexBuffer = function () {
  55707. if (this._useInstancing) {
  55708. return;
  55709. }
  55710. var indices = [];
  55711. var index = 0;
  55712. for (var count = 0; count < this._capacity; count++) {
  55713. indices.push(index);
  55714. indices.push(index + 1);
  55715. indices.push(index + 2);
  55716. indices.push(index);
  55717. indices.push(index + 2);
  55718. indices.push(index + 3);
  55719. index += 4;
  55720. }
  55721. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55722. };
  55723. /**
  55724. * Gets the maximum number of particles active at the same time.
  55725. * @returns The max number of active particles.
  55726. */
  55727. ParticleSystem.prototype.getCapacity = function () {
  55728. return this._capacity;
  55729. };
  55730. /**
  55731. * Gets Wether there are still active particles in the system.
  55732. * @returns True if it is alive, otherwise false.
  55733. */
  55734. ParticleSystem.prototype.isAlive = function () {
  55735. return this._alive;
  55736. };
  55737. /**
  55738. * Gets Wether the system has been started.
  55739. * @returns True if it has been started, otherwise false.
  55740. */
  55741. ParticleSystem.prototype.isStarted = function () {
  55742. return this._started;
  55743. };
  55744. /**
  55745. * Starts the particle system and begins to emit
  55746. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  55747. */
  55748. ParticleSystem.prototype.start = function (delay) {
  55749. var _this = this;
  55750. if (delay === void 0) { delay = 0; }
  55751. if (delay) {
  55752. setTimeout(function () {
  55753. _this.start(0);
  55754. }, delay);
  55755. return;
  55756. }
  55757. this._started = true;
  55758. this._stopped = false;
  55759. this._actualFrame = 0;
  55760. if (this.subEmitters && this.subEmitters.length != 0) {
  55761. this.activeSubSystems = new Array();
  55762. }
  55763. if (this.preWarmCycles) {
  55764. for (var index = 0; index < this.preWarmCycles; index++) {
  55765. this.animate(true);
  55766. }
  55767. }
  55768. };
  55769. /**
  55770. * Stops the particle system.
  55771. * @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.
  55772. */
  55773. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55774. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55775. this._stopped = true;
  55776. if (stopSubEmitters) {
  55777. this._stopSubEmitters();
  55778. }
  55779. };
  55780. // animation sheet
  55781. /**
  55782. * Remove all active particles
  55783. */
  55784. ParticleSystem.prototype.reset = function () {
  55785. this._stockParticles = [];
  55786. this._particles = [];
  55787. };
  55788. /**
  55789. * @hidden (for internal use only)
  55790. */
  55791. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55792. var offset = index * this._vertexBufferSize;
  55793. this._vertexData[offset++] = particle.position.x;
  55794. this._vertexData[offset++] = particle.position.y;
  55795. this._vertexData[offset++] = particle.position.z;
  55796. this._vertexData[offset++] = particle.color.r;
  55797. this._vertexData[offset++] = particle.color.g;
  55798. this._vertexData[offset++] = particle.color.b;
  55799. this._vertexData[offset++] = particle.color.a;
  55800. this._vertexData[offset++] = particle.angle;
  55801. this._vertexData[offset++] = particle.scale.x * particle.size;
  55802. this._vertexData[offset++] = particle.scale.y * particle.size;
  55803. if (this._isAnimationSheetEnabled) {
  55804. this._vertexData[offset++] = particle.cellIndex;
  55805. }
  55806. if (!this._isBillboardBased) {
  55807. if (particle._initialDirection) {
  55808. this._vertexData[offset++] = particle._initialDirection.x;
  55809. this._vertexData[offset++] = particle._initialDirection.y;
  55810. this._vertexData[offset++] = particle._initialDirection.z;
  55811. }
  55812. else {
  55813. this._vertexData[offset++] = particle.direction.x;
  55814. this._vertexData[offset++] = particle.direction.y;
  55815. this._vertexData[offset++] = particle.direction.z;
  55816. }
  55817. }
  55818. if (!this._useInstancing) {
  55819. if (this._isAnimationSheetEnabled) {
  55820. if (offsetX === 0)
  55821. offsetX = this._epsilon;
  55822. else if (offsetX === 1)
  55823. offsetX = 1 - this._epsilon;
  55824. if (offsetY === 0)
  55825. offsetY = this._epsilon;
  55826. else if (offsetY === 1)
  55827. offsetY = 1 - this._epsilon;
  55828. }
  55829. this._vertexData[offset++] = offsetX;
  55830. this._vertexData[offset++] = offsetY;
  55831. }
  55832. };
  55833. ParticleSystem.prototype._stopSubEmitters = function () {
  55834. if (!this.activeSubSystems) {
  55835. return;
  55836. }
  55837. this.activeSubSystems.forEach(function (subSystem) {
  55838. subSystem.stop(true);
  55839. });
  55840. this.activeSubSystems = new Array();
  55841. };
  55842. ParticleSystem.prototype._removeFromRoot = function () {
  55843. if (!this._rootParticleSystem) {
  55844. return;
  55845. }
  55846. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55847. if (index !== -1) {
  55848. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55849. }
  55850. };
  55851. // End of sub system methods
  55852. ParticleSystem.prototype._update = function (newParticles) {
  55853. // Update current
  55854. this._alive = this._particles.length > 0;
  55855. if (this.emitter.position) {
  55856. var emitterMesh = this.emitter;
  55857. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  55858. }
  55859. else {
  55860. var emitterPosition = this.emitter;
  55861. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55862. }
  55863. this.updateFunction(this._particles);
  55864. // Add new ones
  55865. var particle;
  55866. var _loop_2 = function () {
  55867. if (this_1._particles.length === this_1._capacity) {
  55868. return "break";
  55869. }
  55870. particle = this_1._createParticle();
  55871. this_1._particles.push(particle);
  55872. // Emitter
  55873. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55874. if (this_1.startPositionFunction) {
  55875. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  55876. }
  55877. else {
  55878. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  55879. }
  55880. if (this_1.startDirectionFunction) {
  55881. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  55882. }
  55883. else {
  55884. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  55885. }
  55886. if (emitPower === 0) {
  55887. if (!particle._initialDirection) {
  55888. particle._initialDirection = particle.direction.clone();
  55889. }
  55890. else {
  55891. particle._initialDirection.copyFrom(particle.direction);
  55892. }
  55893. }
  55894. else {
  55895. particle._initialDirection = null;
  55896. }
  55897. particle.direction.scaleInPlace(emitPower);
  55898. // Life time
  55899. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55900. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55901. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55902. var factorGradient1 = currentGradient;
  55903. var factorGradient2 = nextGradient;
  55904. var lifeTime1 = factorGradient1.getFactor();
  55905. var lifeTime2 = factorGradient2.getFactor();
  55906. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55907. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55908. });
  55909. }
  55910. else {
  55911. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55912. }
  55913. // Size
  55914. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55915. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55916. }
  55917. else {
  55918. particle._currentSizeGradient = this_1._sizeGradients[0];
  55919. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55920. particle.size = particle._currentSize1;
  55921. if (this_1._sizeGradients.length > 1) {
  55922. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55923. }
  55924. else {
  55925. particle._currentSize2 = particle._currentSize1;
  55926. }
  55927. }
  55928. // Size and scale
  55929. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55930. // Angle
  55931. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55932. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55933. }
  55934. else {
  55935. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55936. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55937. particle._currentAngularSpeed1 = particle.angularSpeed;
  55938. if (this_1._angularSpeedGradients.length > 1) {
  55939. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55940. }
  55941. else {
  55942. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55943. }
  55944. }
  55945. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55946. // Velocity
  55947. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55948. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55949. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55950. if (this_1._velocityGradients.length > 1) {
  55951. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55952. }
  55953. else {
  55954. particle._currentVelocity2 = particle._currentVelocity1;
  55955. }
  55956. }
  55957. // Color
  55958. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55959. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55960. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55961. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55962. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55963. }
  55964. else {
  55965. particle._currentColorGradient = this_1._colorGradients[0];
  55966. particle._currentColorGradient.getColorToRef(particle.color);
  55967. particle._currentColor1.copyFrom(particle.color);
  55968. if (this_1._colorGradients.length > 1) {
  55969. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55970. }
  55971. else {
  55972. particle._currentColor2.copyFrom(particle.color);
  55973. }
  55974. }
  55975. // Sheet
  55976. if (this_1._isAnimationSheetEnabled) {
  55977. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55978. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55979. }
  55980. };
  55981. var this_1 = this, step;
  55982. for (var index = 0; index < newParticles; index++) {
  55983. var state_1 = _loop_2();
  55984. if (state_1 === "break")
  55985. break;
  55986. }
  55987. };
  55988. /** @hidden */
  55989. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55990. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55991. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55992. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55993. if (isAnimationSheetEnabled) {
  55994. attributeNamesOrOptions.push("cellIndex");
  55995. }
  55996. if (!isBillboardBased) {
  55997. attributeNamesOrOptions.push("direction");
  55998. }
  55999. return attributeNamesOrOptions;
  56000. };
  56001. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56002. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56003. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  56004. if (isAnimationSheetEnabled) {
  56005. effectCreationOption.push("particlesInfos");
  56006. }
  56007. return effectCreationOption;
  56008. };
  56009. ParticleSystem.prototype._getEffect = function () {
  56010. if (this._customEffect) {
  56011. return this._customEffect;
  56012. }
  56013. ;
  56014. var defines = [];
  56015. if (this._scene.clipPlane) {
  56016. defines.push("#define CLIPPLANE");
  56017. }
  56018. if (this._isAnimationSheetEnabled) {
  56019. defines.push("#define ANIMATESHEET");
  56020. }
  56021. if (this._isBillboardBased) {
  56022. defines.push("#define BILLBOARD");
  56023. switch (this.billboardMode) {
  56024. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56025. defines.push("#define BILLBOARDY");
  56026. break;
  56027. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56028. default:
  56029. break;
  56030. }
  56031. }
  56032. // Effect
  56033. var join = defines.join("\n");
  56034. if (this._cachedDefines !== join) {
  56035. this._cachedDefines = join;
  56036. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56037. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56038. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56039. }
  56040. return this._effect;
  56041. };
  56042. /**
  56043. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56044. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56045. */
  56046. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56047. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56048. if (!this._started)
  56049. return;
  56050. if (!preWarmOnly) {
  56051. var effect = this._getEffect();
  56052. // Check
  56053. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56054. return;
  56055. if (this._currentRenderId === this._scene.getRenderId()) {
  56056. return;
  56057. }
  56058. this._currentRenderId = this._scene.getRenderId();
  56059. }
  56060. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56061. // determine the number of particles we need to create
  56062. var newParticles;
  56063. if (this.manualEmitCount > -1) {
  56064. newParticles = this.manualEmitCount;
  56065. this._newPartsExcess = 0;
  56066. this.manualEmitCount = 0;
  56067. }
  56068. else {
  56069. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56070. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56071. }
  56072. if (this._newPartsExcess > 1.0) {
  56073. newParticles += this._newPartsExcess >> 0;
  56074. this._newPartsExcess -= this._newPartsExcess >> 0;
  56075. }
  56076. this._alive = false;
  56077. if (!this._stopped) {
  56078. this._actualFrame += this._scaledUpdateSpeed;
  56079. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56080. this.stop();
  56081. }
  56082. else {
  56083. newParticles = 0;
  56084. }
  56085. this._update(newParticles);
  56086. // Stopped?
  56087. if (this._stopped) {
  56088. if (!this._alive) {
  56089. this._started = false;
  56090. if (this.onAnimationEnd) {
  56091. this.onAnimationEnd();
  56092. }
  56093. if (this.disposeOnStop) {
  56094. this._scene._toBeDisposed.push(this);
  56095. }
  56096. }
  56097. }
  56098. if (!preWarmOnly) {
  56099. // Update VBO
  56100. var offset = 0;
  56101. for (var index = 0; index < this._particles.length; index++) {
  56102. var particle = this._particles[index];
  56103. this._appendParticleVertices(offset, particle);
  56104. offset += this._useInstancing ? 1 : 4;
  56105. }
  56106. if (this._vertexBuffer) {
  56107. this._vertexBuffer.update(this._vertexData);
  56108. }
  56109. }
  56110. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56111. this.stop();
  56112. }
  56113. };
  56114. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56115. this._appendParticleVertex(offset++, particle, 0, 0);
  56116. if (!this._useInstancing) {
  56117. this._appendParticleVertex(offset++, particle, 1, 0);
  56118. this._appendParticleVertex(offset++, particle, 1, 1);
  56119. this._appendParticleVertex(offset++, particle, 0, 1);
  56120. }
  56121. };
  56122. /**
  56123. * Rebuilds the particle system.
  56124. */
  56125. ParticleSystem.prototype.rebuild = function () {
  56126. this._createIndexBuffer();
  56127. if (this._vertexBuffer) {
  56128. this._vertexBuffer._rebuild();
  56129. }
  56130. };
  56131. /**
  56132. * Is this system ready to be used/rendered
  56133. * @return true if the system is ready
  56134. */
  56135. ParticleSystem.prototype.isReady = function () {
  56136. var effect = this._getEffect();
  56137. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56138. return false;
  56139. }
  56140. return true;
  56141. };
  56142. /**
  56143. * Renders the particle system in its current state.
  56144. * @returns the current number of particles
  56145. */
  56146. ParticleSystem.prototype.render = function () {
  56147. var effect = this._getEffect();
  56148. // Check
  56149. if (!this.isReady() || !this._particles.length) {
  56150. return 0;
  56151. }
  56152. var engine = this._scene.getEngine();
  56153. // Render
  56154. engine.enableEffect(effect);
  56155. engine.setState(false);
  56156. var viewMatrix = this._scene.getViewMatrix();
  56157. effect.setTexture("diffuseSampler", this.particleTexture);
  56158. effect.setMatrix("view", viewMatrix);
  56159. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56160. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56161. var baseSize = this.particleTexture.getBaseSize();
  56162. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56163. }
  56164. effect.setVector2("translationPivot", this.translationPivot);
  56165. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56166. if (this._isBillboardBased) {
  56167. var camera = this._scene.activeCamera;
  56168. effect.setVector3("eyePosition", camera.globalPosition);
  56169. }
  56170. if (this._scene.clipPlane) {
  56171. var clipPlane = this._scene.clipPlane;
  56172. var invView = viewMatrix.clone();
  56173. invView.invert();
  56174. effect.setMatrix("invView", invView);
  56175. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56176. }
  56177. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56178. // Draw order
  56179. switch (this.blendMode) {
  56180. case ParticleSystem.BLENDMODE_ADD:
  56181. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56182. break;
  56183. case ParticleSystem.BLENDMODE_ONEONE:
  56184. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56185. break;
  56186. case ParticleSystem.BLENDMODE_STANDARD:
  56187. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56188. break;
  56189. }
  56190. if (this.forceDepthWrite) {
  56191. engine.setDepthWrite(true);
  56192. }
  56193. if (this._useInstancing) {
  56194. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56195. engine.unbindInstanceAttributes();
  56196. }
  56197. else {
  56198. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56199. }
  56200. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56201. return this._particles.length;
  56202. };
  56203. /**
  56204. * Disposes the particle system and free the associated resources
  56205. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56206. */
  56207. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56208. if (disposeTexture === void 0) { disposeTexture = true; }
  56209. if (this._vertexBuffer) {
  56210. this._vertexBuffer.dispose();
  56211. this._vertexBuffer = null;
  56212. }
  56213. if (this._spriteBuffer) {
  56214. this._spriteBuffer.dispose();
  56215. this._spriteBuffer = null;
  56216. }
  56217. if (this._indexBuffer) {
  56218. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56219. this._indexBuffer = null;
  56220. }
  56221. if (disposeTexture && this.particleTexture) {
  56222. this.particleTexture.dispose();
  56223. this.particleTexture = null;
  56224. }
  56225. if (disposeTexture && this.noiseTexture) {
  56226. this.noiseTexture.dispose();
  56227. this.noiseTexture = null;
  56228. }
  56229. this._removeFromRoot();
  56230. // Remove from scene
  56231. var index = this._scene.particleSystems.indexOf(this);
  56232. if (index > -1) {
  56233. this._scene.particleSystems.splice(index, 1);
  56234. }
  56235. // Callback
  56236. this.onDisposeObservable.notifyObservers(this);
  56237. this.onDisposeObservable.clear();
  56238. };
  56239. /**
  56240. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56241. * @param radius The radius of the sphere to emit from
  56242. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56243. * @returns the emitter
  56244. */
  56245. ParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56246. if (radius === void 0) { radius = 1; }
  56247. if (radiusRange === void 0) { radiusRange = 1; }
  56248. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56249. this.particleEmitterType = particleEmitter;
  56250. return particleEmitter;
  56251. };
  56252. /**
  56253. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56254. * @param radius The radius of the sphere to emit from
  56255. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56256. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56257. * @returns the emitter
  56258. */
  56259. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56260. if (radius === void 0) { radius = 1; }
  56261. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56262. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56263. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56264. this.particleEmitterType = particleEmitter;
  56265. return particleEmitter;
  56266. };
  56267. /**
  56268. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56269. * @param radius The radius of the cone to emit from
  56270. * @param angle The base angle of the cone
  56271. * @returns the emitter
  56272. */
  56273. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56274. if (radius === void 0) { radius = 1; }
  56275. if (angle === void 0) { angle = Math.PI / 4; }
  56276. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56277. this.particleEmitterType = particleEmitter;
  56278. return particleEmitter;
  56279. };
  56280. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56281. /**
  56282. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56283. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56284. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56285. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56286. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56287. * @returns the emitter
  56288. */
  56289. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56290. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56291. this.particleEmitterType = particleEmitter;
  56292. this.direction1 = direction1;
  56293. this.direction2 = direction2;
  56294. this.minEmitBox = minEmitBox;
  56295. this.maxEmitBox = maxEmitBox;
  56296. return particleEmitter;
  56297. };
  56298. // Clone
  56299. /**
  56300. * Clones the particle system.
  56301. * @param name The name of the cloned object
  56302. * @param newEmitter The new emitter to use
  56303. * @returns the cloned particle system
  56304. */
  56305. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56306. var custom = null;
  56307. var program = null;
  56308. if (this.customShader != null) {
  56309. program = this.customShader;
  56310. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56311. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56312. }
  56313. else if (this._customEffect) {
  56314. custom = this._customEffect;
  56315. }
  56316. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56317. result.customShader = program;
  56318. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56319. if (newEmitter === undefined) {
  56320. newEmitter = this.emitter;
  56321. }
  56322. result.emitter = newEmitter;
  56323. if (this.particleTexture) {
  56324. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56325. }
  56326. if (!this.preventAutoStart) {
  56327. result.start();
  56328. }
  56329. return result;
  56330. };
  56331. /**
  56332. * Serializes the particle system to a JSON object.
  56333. * @returns the JSON object
  56334. */
  56335. ParticleSystem.prototype.serialize = function () {
  56336. var serializationObject = {};
  56337. ParticleSystem._Serialize(serializationObject, this);
  56338. serializationObject.textureMask = this.textureMask.asArray();
  56339. serializationObject.customShader = this.customShader;
  56340. serializationObject.preventAutoStart = this.preventAutoStart;
  56341. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56342. return serializationObject;
  56343. };
  56344. /** @hidden */
  56345. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56346. serializationObject.name = particleSystem.name;
  56347. serializationObject.id = particleSystem.id;
  56348. serializationObject.capacity = particleSystem.getCapacity();
  56349. // Emitter
  56350. if (particleSystem.emitter.position) {
  56351. var emitterMesh = particleSystem.emitter;
  56352. serializationObject.emitterId = emitterMesh.id;
  56353. }
  56354. else {
  56355. var emitterPosition = particleSystem.emitter;
  56356. serializationObject.emitter = emitterPosition.asArray();
  56357. }
  56358. // Emitter
  56359. if (particleSystem.particleEmitterType) {
  56360. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56361. }
  56362. if (particleSystem.particleTexture) {
  56363. serializationObject.textureName = particleSystem.particleTexture.name;
  56364. }
  56365. // Animations
  56366. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56367. // Particle system
  56368. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56369. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56370. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56371. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56372. serializationObject.minSize = particleSystem.minSize;
  56373. serializationObject.maxSize = particleSystem.maxSize;
  56374. serializationObject.minScaleX = particleSystem.minScaleX;
  56375. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56376. serializationObject.minScaleY = particleSystem.minScaleY;
  56377. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56378. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56379. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56380. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56381. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56382. serializationObject.emitRate = particleSystem.emitRate;
  56383. serializationObject.gravity = particleSystem.gravity.asArray();
  56384. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  56385. serializationObject.color1 = particleSystem.color1.asArray();
  56386. serializationObject.color2 = particleSystem.color2.asArray();
  56387. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56388. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56389. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56390. serializationObject.blendMode = particleSystem.blendMode;
  56391. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56392. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56393. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56394. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56395. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56396. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56397. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56398. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56399. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56400. var colorGradients = particleSystem.getColorGradients();
  56401. if (colorGradients) {
  56402. serializationObject.colorGradients = [];
  56403. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56404. var colorGradient = colorGradients_1[_i];
  56405. var serializedGradient = {
  56406. gradient: colorGradient.gradient,
  56407. color1: colorGradient.color1.asArray()
  56408. };
  56409. if (colorGradient.color2) {
  56410. serializedGradient.color2 = colorGradient.color2.asArray();
  56411. }
  56412. serializationObject.colorGradients.push(serializedGradient);
  56413. }
  56414. }
  56415. var sizeGradients = particleSystem.getSizeGradients();
  56416. if (sizeGradients) {
  56417. serializationObject.sizeGradients = [];
  56418. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56419. var sizeGradient = sizeGradients_1[_a];
  56420. var serializedGradient = {
  56421. gradient: sizeGradient.gradient,
  56422. factor1: sizeGradient.factor1
  56423. };
  56424. if (sizeGradient.factor2 !== undefined) {
  56425. serializedGradient.factor2 = sizeGradient.factor2;
  56426. }
  56427. serializationObject.sizeGradients.push(serializedGradient);
  56428. }
  56429. }
  56430. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56431. if (angularSpeedGradients) {
  56432. serializationObject.angularSpeedGradients = [];
  56433. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56434. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56435. var serializedGradient = {
  56436. gradient: angularSpeedGradient.gradient,
  56437. factor1: angularSpeedGradient.factor1
  56438. };
  56439. if (angularSpeedGradient.factor2 !== undefined) {
  56440. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56441. }
  56442. serializationObject.angularSpeedGradients.push(serializedGradient);
  56443. }
  56444. }
  56445. var velocityGradients = particleSystem.getVelocityGradients();
  56446. if (velocityGradients) {
  56447. serializationObject.velocityGradients = [];
  56448. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56449. var velocityGradient = velocityGradients_1[_c];
  56450. var serializedGradient = {
  56451. gradient: velocityGradient.gradient,
  56452. factor1: velocityGradient.factor1
  56453. };
  56454. if (velocityGradient.factor2 !== undefined) {
  56455. serializedGradient.factor2 = velocityGradient.factor2;
  56456. }
  56457. serializationObject.velocityGradients.push(serializedGradient);
  56458. }
  56459. }
  56460. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  56461. var noiseTexture = particleSystem.noiseTexture;
  56462. serializationObject.noiseTexture = noiseTexture.serialize();
  56463. }
  56464. };
  56465. /** @hidden */
  56466. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56467. // Texture
  56468. if (parsedParticleSystem.textureName) {
  56469. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56470. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56471. }
  56472. // Emitter
  56473. if (parsedParticleSystem.emitterId === undefined) {
  56474. particleSystem.emitter = BABYLON.Vector3.Zero();
  56475. }
  56476. else if (parsedParticleSystem.emitterId) {
  56477. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56478. }
  56479. else {
  56480. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56481. }
  56482. // Misc.
  56483. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56484. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56485. }
  56486. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56487. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56488. }
  56489. // Animations
  56490. if (parsedParticleSystem.animations) {
  56491. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56492. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56493. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56494. }
  56495. }
  56496. if (parsedParticleSystem.autoAnimate) {
  56497. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56498. }
  56499. // Particle system
  56500. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56501. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56502. particleSystem.minSize = parsedParticleSystem.minSize;
  56503. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56504. if (parsedParticleSystem.minScaleX) {
  56505. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56506. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56507. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56508. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56509. }
  56510. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56511. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56512. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56513. }
  56514. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56515. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56516. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56517. }
  56518. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56519. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56520. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56521. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56522. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56523. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56524. if (parsedParticleSystem.noiseStrength) {
  56525. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  56526. }
  56527. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56528. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56529. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56530. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56531. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56532. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56533. if (parsedParticleSystem.colorGradients) {
  56534. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56535. var colorGradient = _a[_i];
  56536. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56537. }
  56538. }
  56539. if (parsedParticleSystem.sizeGradients) {
  56540. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56541. var sizeGradient = _c[_b];
  56542. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56543. }
  56544. }
  56545. if (parsedParticleSystem.angularSpeedGradients) {
  56546. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56547. var angularSpeedGradient = _e[_d];
  56548. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56549. }
  56550. }
  56551. if (parsedParticleSystem.velocityGradients) {
  56552. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56553. var velocityGradient = _g[_f];
  56554. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56555. }
  56556. }
  56557. if (parsedParticleSystem.noiseTexture) {
  56558. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  56559. }
  56560. // Emitter
  56561. var emitterType;
  56562. if (parsedParticleSystem.particleEmitterType) {
  56563. switch (parsedParticleSystem.particleEmitterType.type) {
  56564. case "SphereParticleEmitter":
  56565. emitterType = new BABYLON.SphereParticleEmitter();
  56566. break;
  56567. case "SphereDirectedParticleEmitter":
  56568. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56569. break;
  56570. case "ConeEmitter":
  56571. case "ConeParticleEmitter":
  56572. emitterType = new BABYLON.ConeParticleEmitter();
  56573. break;
  56574. case "BoxEmitter":
  56575. case "BoxParticleEmitter":
  56576. default:
  56577. emitterType = new BABYLON.BoxParticleEmitter();
  56578. break;
  56579. }
  56580. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56581. }
  56582. else {
  56583. emitterType = new BABYLON.BoxParticleEmitter();
  56584. emitterType.parse(parsedParticleSystem);
  56585. }
  56586. particleSystem.particleEmitterType = emitterType;
  56587. // Animation sheet
  56588. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56589. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56590. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56591. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56592. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56593. };
  56594. /**
  56595. * Parses a JSON object to create a particle system.
  56596. * @param parsedParticleSystem The JSON object to parse
  56597. * @param scene The scene to create the particle system in
  56598. * @param rootUrl The root url to use to load external dependencies like texture
  56599. * @returns the Parsed particle system
  56600. */
  56601. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56602. var name = parsedParticleSystem.name;
  56603. var custom = null;
  56604. var program = null;
  56605. if (parsedParticleSystem.customShader) {
  56606. program = parsedParticleSystem.customShader;
  56607. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56608. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56609. }
  56610. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56611. particleSystem.customShader = program;
  56612. if (parsedParticleSystem.id) {
  56613. particleSystem.id = parsedParticleSystem.id;
  56614. }
  56615. // Auto start
  56616. if (parsedParticleSystem.preventAutoStart) {
  56617. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56618. }
  56619. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56620. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56621. if (!particleSystem.preventAutoStart) {
  56622. particleSystem.start();
  56623. }
  56624. return particleSystem;
  56625. };
  56626. /**
  56627. * Source color is added to the destination color without alpha affecting the result.
  56628. */
  56629. ParticleSystem.BLENDMODE_ONEONE = 0;
  56630. /**
  56631. * Blend current color and particle color using particle’s alpha.
  56632. */
  56633. ParticleSystem.BLENDMODE_STANDARD = 1;
  56634. /**
  56635. * Add current color and particle color multiplied by particle’s alpha.
  56636. */
  56637. ParticleSystem.BLENDMODE_ADD = 2;
  56638. return ParticleSystem;
  56639. }());
  56640. BABYLON.ParticleSystem = ParticleSystem;
  56641. })(BABYLON || (BABYLON = {}));
  56642. //# sourceMappingURL=babylon.particleSystem.js.map
  56643. var BABYLON;
  56644. (function (BABYLON) {
  56645. /**
  56646. * Particle emitter emitting particles from the inside of a box.
  56647. * It emits the particles randomly between 2 given directions.
  56648. */
  56649. var BoxParticleEmitter = /** @class */ (function () {
  56650. /**
  56651. * Creates a new instance BoxParticleEmitter
  56652. */
  56653. function BoxParticleEmitter() {
  56654. /**
  56655. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56656. */
  56657. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56658. /**
  56659. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56660. */
  56661. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56662. /**
  56663. * 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.
  56664. */
  56665. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56666. /**
  56667. * 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.
  56668. */
  56669. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56670. }
  56671. /**
  56672. * Called by the particle System when the direction is computed for the created particle.
  56673. * @param worldMatrix is the world matrix of the particle system
  56674. * @param directionToUpdate is the direction vector to update with the result
  56675. * @param particle is the particle we are computed the direction for
  56676. */
  56677. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56678. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56679. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56680. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56681. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56682. };
  56683. /**
  56684. * Called by the particle System when the position is computed for the created particle.
  56685. * @param worldMatrix is the world matrix of the particle system
  56686. * @param positionToUpdate is the position vector to update with the result
  56687. * @param particle is the particle we are computed the position for
  56688. */
  56689. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56690. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56691. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56692. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56693. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56694. };
  56695. /**
  56696. * Clones the current emitter and returns a copy of it
  56697. * @returns the new emitter
  56698. */
  56699. BoxParticleEmitter.prototype.clone = function () {
  56700. var newOne = new BoxParticleEmitter();
  56701. BABYLON.Tools.DeepCopy(this, newOne);
  56702. return newOne;
  56703. };
  56704. /**
  56705. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56706. * @param effect defines the update shader
  56707. */
  56708. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56709. effect.setVector3("direction1", this.direction1);
  56710. effect.setVector3("direction2", this.direction2);
  56711. effect.setVector3("minEmitBox", this.minEmitBox);
  56712. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56713. };
  56714. /**
  56715. * Returns a string to use to update the GPU particles update shader
  56716. * @returns a string containng the defines string
  56717. */
  56718. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56719. return "#define BOXEMITTER";
  56720. };
  56721. /**
  56722. * Returns the string "BoxParticleEmitter"
  56723. * @returns a string containing the class name
  56724. */
  56725. BoxParticleEmitter.prototype.getClassName = function () {
  56726. return "BoxParticleEmitter";
  56727. };
  56728. /**
  56729. * Serializes the particle system to a JSON object.
  56730. * @returns the JSON object
  56731. */
  56732. BoxParticleEmitter.prototype.serialize = function () {
  56733. var serializationObject = {};
  56734. serializationObject.type = this.getClassName();
  56735. serializationObject.direction1 = this.direction1.asArray();
  56736. serializationObject.direction2 = this.direction2.asArray();
  56737. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56738. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56739. return serializationObject;
  56740. };
  56741. /**
  56742. * Parse properties from a JSON object
  56743. * @param serializationObject defines the JSON object
  56744. */
  56745. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56746. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56747. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56748. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56749. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56750. };
  56751. return BoxParticleEmitter;
  56752. }());
  56753. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56754. })(BABYLON || (BABYLON = {}));
  56755. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56756. var BABYLON;
  56757. (function (BABYLON) {
  56758. /**
  56759. * Particle emitter emitting particles from the inside of a cone.
  56760. * It emits the particles alongside the cone volume from the base to the particle.
  56761. * The emission direction might be randomized.
  56762. */
  56763. var ConeParticleEmitter = /** @class */ (function () {
  56764. /**
  56765. * Creates a new instance ConeParticleEmitter
  56766. * @param radius the radius of the emission cone (1 by default)
  56767. * @param angles the cone base angle (PI by default)
  56768. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56769. */
  56770. function ConeParticleEmitter(radius, angle,
  56771. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56772. directionRandomizer) {
  56773. if (radius === void 0) { radius = 1; }
  56774. if (angle === void 0) { angle = Math.PI; }
  56775. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56776. this.directionRandomizer = directionRandomizer;
  56777. /**
  56778. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56779. */
  56780. this.radiusRange = 1;
  56781. /**
  56782. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56783. */
  56784. this.heightRange = 1;
  56785. this.angle = angle;
  56786. this.radius = radius;
  56787. }
  56788. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56789. /**
  56790. * Gets or sets the radius of the emission cone
  56791. */
  56792. get: function () {
  56793. return this._radius;
  56794. },
  56795. set: function (value) {
  56796. this._radius = value;
  56797. this._buildHeight();
  56798. },
  56799. enumerable: true,
  56800. configurable: true
  56801. });
  56802. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56803. /**
  56804. * Gets or sets the angle of the emission cone
  56805. */
  56806. get: function () {
  56807. return this._angle;
  56808. },
  56809. set: function (value) {
  56810. this._angle = value;
  56811. this._buildHeight();
  56812. },
  56813. enumerable: true,
  56814. configurable: true
  56815. });
  56816. ConeParticleEmitter.prototype._buildHeight = function () {
  56817. if (this._angle !== 0) {
  56818. this._height = this._radius / Math.tan(this._angle / 2);
  56819. }
  56820. else {
  56821. this._height = 1;
  56822. }
  56823. };
  56824. /**
  56825. * Called by the particle System when the direction is computed for the created particle.
  56826. * @param worldMatrix is the world matrix of the particle system
  56827. * @param directionToUpdate is the direction vector to update with the result
  56828. * @param particle is the particle we are computed the direction for
  56829. */
  56830. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56831. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56832. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56833. }
  56834. else {
  56835. // measure the direction Vector from the emitter to the particle.
  56836. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56837. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56838. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56839. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56840. direction.x += randX;
  56841. direction.y += randY;
  56842. direction.z += randZ;
  56843. direction.normalize();
  56844. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56845. }
  56846. };
  56847. /**
  56848. * Called by the particle System when the position is computed for the created particle.
  56849. * @param worldMatrix is the world matrix of the particle system
  56850. * @param positionToUpdate is the position vector to update with the result
  56851. * @param particle is the particle we are computed the position for
  56852. */
  56853. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56854. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56855. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56856. // Better distribution in a cone at normal angles.
  56857. h = 1 - h * h;
  56858. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56859. radius = radius * h;
  56860. var randX = radius * Math.sin(s);
  56861. var randZ = radius * Math.cos(s);
  56862. var randY = h * this._height;
  56863. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56864. };
  56865. /**
  56866. * Clones the current emitter and returns a copy of it
  56867. * @returns the new emitter
  56868. */
  56869. ConeParticleEmitter.prototype.clone = function () {
  56870. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56871. BABYLON.Tools.DeepCopy(this, newOne);
  56872. return newOne;
  56873. };
  56874. /**
  56875. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56876. * @param effect defines the update shader
  56877. */
  56878. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56879. effect.setFloat2("radius", this._radius, this.radiusRange);
  56880. effect.setFloat("coneAngle", this._angle);
  56881. effect.setFloat2("height", this._height, this.heightRange);
  56882. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56883. };
  56884. /**
  56885. * Returns a string to use to update the GPU particles update shader
  56886. * @returns a string containng the defines string
  56887. */
  56888. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56889. return "#define CONEEMITTER";
  56890. };
  56891. /**
  56892. * Returns the string "ConeParticleEmitter"
  56893. * @returns a string containing the class name
  56894. */
  56895. ConeParticleEmitter.prototype.getClassName = function () {
  56896. return "ConeParticleEmitter";
  56897. };
  56898. /**
  56899. * Serializes the particle system to a JSON object.
  56900. * @returns the JSON object
  56901. */
  56902. ConeParticleEmitter.prototype.serialize = function () {
  56903. var serializationObject = {};
  56904. serializationObject.type = this.getClassName();
  56905. serializationObject.radius = this._radius;
  56906. serializationObject.angle = this._angle;
  56907. serializationObject.directionRandomizer = this.directionRandomizer;
  56908. return serializationObject;
  56909. };
  56910. /**
  56911. * Parse properties from a JSON object
  56912. * @param serializationObject defines the JSON object
  56913. */
  56914. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56915. this.radius = serializationObject.radius;
  56916. this.angle = serializationObject.angle;
  56917. this.directionRandomizer = serializationObject.directionRandomizer;
  56918. };
  56919. return ConeParticleEmitter;
  56920. }());
  56921. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56922. })(BABYLON || (BABYLON = {}));
  56923. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56924. var BABYLON;
  56925. (function (BABYLON) {
  56926. /**
  56927. * Particle emitter emitting particles from the inside of a sphere.
  56928. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56929. */
  56930. var SphereParticleEmitter = /** @class */ (function () {
  56931. /**
  56932. * Creates a new instance SphereParticleEmitter
  56933. * @param radius the radius of the emission sphere (1 by default)
  56934. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56935. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56936. */
  56937. function SphereParticleEmitter(
  56938. /**
  56939. * The radius of the emission sphere.
  56940. */
  56941. radius,
  56942. /**
  56943. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  56944. */
  56945. radiusRange,
  56946. /**
  56947. * How much to randomize the particle direction [0-1].
  56948. */
  56949. directionRandomizer) {
  56950. if (radius === void 0) { radius = 1; }
  56951. if (radiusRange === void 0) { radiusRange = 1; }
  56952. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56953. this.radius = radius;
  56954. this.radiusRange = radiusRange;
  56955. this.directionRandomizer = directionRandomizer;
  56956. }
  56957. /**
  56958. * Called by the particle System when the direction is computed for the created particle.
  56959. * @param worldMatrix is the world matrix of the particle system
  56960. * @param directionToUpdate is the direction vector to update with the result
  56961. * @param particle is the particle we are computed the direction for
  56962. */
  56963. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56964. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56965. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56966. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56967. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56968. direction.x += randX;
  56969. direction.y += randY;
  56970. direction.z += randZ;
  56971. direction.normalize();
  56972. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56973. };
  56974. /**
  56975. * Called by the particle System when the position is computed for the created particle.
  56976. * @param worldMatrix is the world matrix of the particle system
  56977. * @param positionToUpdate is the position vector to update with the result
  56978. * @param particle is the particle we are computed the position for
  56979. */
  56980. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56981. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56982. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56983. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56984. var theta = Math.acos(2 * v - 1);
  56985. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56986. var randY = randRadius * Math.cos(theta);
  56987. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56988. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56989. };
  56990. /**
  56991. * Clones the current emitter and returns a copy of it
  56992. * @returns the new emitter
  56993. */
  56994. SphereParticleEmitter.prototype.clone = function () {
  56995. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56996. BABYLON.Tools.DeepCopy(this, newOne);
  56997. return newOne;
  56998. };
  56999. /**
  57000. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57001. * @param effect defines the update shader
  57002. */
  57003. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57004. effect.setFloat("radius", this.radius);
  57005. effect.setFloat("radiusRange", this.radiusRange);
  57006. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57007. };
  57008. /**
  57009. * Returns a string to use to update the GPU particles update shader
  57010. * @returns a string containng the defines string
  57011. */
  57012. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57013. return "#define SPHEREEMITTER";
  57014. };
  57015. /**
  57016. * Returns the string "SphereParticleEmitter"
  57017. * @returns a string containing the class name
  57018. */
  57019. SphereParticleEmitter.prototype.getClassName = function () {
  57020. return "SphereParticleEmitter";
  57021. };
  57022. /**
  57023. * Serializes the particle system to a JSON object.
  57024. * @returns the JSON object
  57025. */
  57026. SphereParticleEmitter.prototype.serialize = function () {
  57027. var serializationObject = {};
  57028. serializationObject.type = this.getClassName();
  57029. serializationObject.radius = this.radius;
  57030. serializationObject.radiusRange = this.radiusRange;
  57031. serializationObject.directionRandomizer = this.directionRandomizer;
  57032. return serializationObject;
  57033. };
  57034. /**
  57035. * Parse properties from a JSON object
  57036. * @param serializationObject defines the JSON object
  57037. */
  57038. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57039. this.radius = serializationObject.radius;
  57040. this.radiusRange = serializationObject.radiusRange;
  57041. this.directionRandomizer = serializationObject.directionRandomizer;
  57042. };
  57043. return SphereParticleEmitter;
  57044. }());
  57045. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57046. /**
  57047. * Particle emitter emitting particles from the inside of a sphere.
  57048. * It emits the particles randomly between two vectors.
  57049. */
  57050. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57051. __extends(SphereDirectedParticleEmitter, _super);
  57052. /**
  57053. * Creates a new instance SphereDirectedParticleEmitter
  57054. * @param radius the radius of the emission sphere (1 by default)
  57055. * @param direction1 the min limit of the emission direction (up vector by default)
  57056. * @param direction2 the max limit of the emission direction (up vector by default)
  57057. */
  57058. function SphereDirectedParticleEmitter(radius,
  57059. /**
  57060. * The min limit of the emission direction.
  57061. */
  57062. direction1,
  57063. /**
  57064. * The max limit of the emission direction.
  57065. */
  57066. direction2) {
  57067. if (radius === void 0) { radius = 1; }
  57068. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57069. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57070. var _this = _super.call(this, radius) || this;
  57071. _this.direction1 = direction1;
  57072. _this.direction2 = direction2;
  57073. return _this;
  57074. }
  57075. /**
  57076. * Called by the particle System when the direction is computed for the created particle.
  57077. * @param worldMatrix is the world matrix of the particle system
  57078. * @param directionToUpdate is the direction vector to update with the result
  57079. * @param particle is the particle we are computed the direction for
  57080. */
  57081. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57082. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57083. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57084. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57085. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57086. };
  57087. /**
  57088. * Clones the current emitter and returns a copy of it
  57089. * @returns the new emitter
  57090. */
  57091. SphereDirectedParticleEmitter.prototype.clone = function () {
  57092. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57093. BABYLON.Tools.DeepCopy(this, newOne);
  57094. return newOne;
  57095. };
  57096. /**
  57097. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57098. * @param effect defines the update shader
  57099. */
  57100. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57101. effect.setFloat("radius", this.radius);
  57102. effect.setFloat("radiusRange", this.radiusRange);
  57103. effect.setVector3("direction1", this.direction1);
  57104. effect.setVector3("direction2", this.direction2);
  57105. };
  57106. /**
  57107. * Returns a string to use to update the GPU particles update shader
  57108. * @returns a string containng the defines string
  57109. */
  57110. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57111. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57112. };
  57113. /**
  57114. * Returns the string "SphereDirectedParticleEmitter"
  57115. * @returns a string containing the class name
  57116. */
  57117. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57118. return "SphereDirectedParticleEmitter";
  57119. };
  57120. /**
  57121. * Serializes the particle system to a JSON object.
  57122. * @returns the JSON object
  57123. */
  57124. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57125. var serializationObject = _super.prototype.serialize.call(this);
  57126. serializationObject.direction1 = this.direction1.asArray();
  57127. serializationObject.direction2 = this.direction2.asArray();
  57128. return serializationObject;
  57129. };
  57130. /**
  57131. * Parse properties from a JSON object
  57132. * @param serializationObject defines the JSON object
  57133. */
  57134. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57135. _super.prototype.parse.call(this, serializationObject);
  57136. this.direction1.copyFrom(serializationObject.direction1);
  57137. this.direction2.copyFrom(serializationObject.direction2);
  57138. };
  57139. return SphereDirectedParticleEmitter;
  57140. }(SphereParticleEmitter));
  57141. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57142. })(BABYLON || (BABYLON = {}));
  57143. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57144. var BABYLON;
  57145. (function (BABYLON) {
  57146. // Adds the parsers to the scene parsers.
  57147. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57148. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  57149. if (!individualParser) {
  57150. return;
  57151. }
  57152. // Particles Systems
  57153. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57154. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57155. var parsedParticleSystem = parsedData.particleSystems[index];
  57156. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  57157. }
  57158. }
  57159. });
  57160. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  57161. if (parsedParticleSystem.activeParticleCount) {
  57162. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57163. return ps;
  57164. }
  57165. else {
  57166. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57167. return ps;
  57168. }
  57169. });
  57170. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57171. if (uniformsNames === void 0) { uniformsNames = []; }
  57172. if (samplers === void 0) { samplers = []; }
  57173. if (defines === void 0) { defines = ""; }
  57174. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57175. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57176. if (defines.indexOf(" BILLBOARD") === -1) {
  57177. defines += "\n#define BILLBOARD\n";
  57178. }
  57179. if (samplers.indexOf("diffuseSampler") === -1) {
  57180. samplers.push("diffuseSampler");
  57181. }
  57182. return this.createEffect({
  57183. vertex: "particles",
  57184. fragmentElement: fragmentName
  57185. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57186. };
  57187. })(BABYLON || (BABYLON = {}));
  57188. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57189. var BABYLON;
  57190. (function (BABYLON) {
  57191. var ShaderMaterial = /** @class */ (function (_super) {
  57192. __extends(ShaderMaterial, _super);
  57193. function ShaderMaterial(name, scene, shaderPath, options) {
  57194. var _this = _super.call(this, name, scene) || this;
  57195. _this._textures = {};
  57196. _this._textureArrays = {};
  57197. _this._floats = {};
  57198. _this._ints = {};
  57199. _this._floatsArrays = {};
  57200. _this._colors3 = {};
  57201. _this._colors3Arrays = {};
  57202. _this._colors4 = {};
  57203. _this._vectors2 = {};
  57204. _this._vectors3 = {};
  57205. _this._vectors4 = {};
  57206. _this._matrices = {};
  57207. _this._matrices3x3 = {};
  57208. _this._matrices2x2 = {};
  57209. _this._vectors2Arrays = {};
  57210. _this._vectors3Arrays = {};
  57211. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57212. _this._shaderPath = shaderPath;
  57213. options.needAlphaBlending = options.needAlphaBlending || false;
  57214. options.needAlphaTesting = options.needAlphaTesting || false;
  57215. options.attributes = options.attributes || ["position", "normal", "uv"];
  57216. options.uniforms = options.uniforms || ["worldViewProjection"];
  57217. options.uniformBuffers = options.uniformBuffers || [];
  57218. options.samplers = options.samplers || [];
  57219. options.defines = options.defines || [];
  57220. _this._options = options;
  57221. return _this;
  57222. }
  57223. ShaderMaterial.prototype.getClassName = function () {
  57224. return "ShaderMaterial";
  57225. };
  57226. ShaderMaterial.prototype.needAlphaBlending = function () {
  57227. return this._options.needAlphaBlending;
  57228. };
  57229. ShaderMaterial.prototype.needAlphaTesting = function () {
  57230. return this._options.needAlphaTesting;
  57231. };
  57232. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57233. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57234. this._options.uniforms.push(uniformName);
  57235. }
  57236. };
  57237. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57238. if (this._options.samplers.indexOf(name) === -1) {
  57239. this._options.samplers.push(name);
  57240. }
  57241. this._textures[name] = texture;
  57242. return this;
  57243. };
  57244. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57245. if (this._options.samplers.indexOf(name) === -1) {
  57246. this._options.samplers.push(name);
  57247. }
  57248. this._checkUniform(name);
  57249. this._textureArrays[name] = textures;
  57250. return this;
  57251. };
  57252. ShaderMaterial.prototype.setFloat = function (name, value) {
  57253. this._checkUniform(name);
  57254. this._floats[name] = value;
  57255. return this;
  57256. };
  57257. ShaderMaterial.prototype.setInt = function (name, value) {
  57258. this._checkUniform(name);
  57259. this._ints[name] = value;
  57260. return this;
  57261. };
  57262. ShaderMaterial.prototype.setFloats = function (name, value) {
  57263. this._checkUniform(name);
  57264. this._floatsArrays[name] = value;
  57265. return this;
  57266. };
  57267. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57268. this._checkUniform(name);
  57269. this._colors3[name] = value;
  57270. return this;
  57271. };
  57272. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57273. this._checkUniform(name);
  57274. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57275. color.toArray(arr, arr.length);
  57276. return arr;
  57277. }, []);
  57278. return this;
  57279. };
  57280. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57281. this._checkUniform(name);
  57282. this._colors4[name] = value;
  57283. return this;
  57284. };
  57285. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57286. this._checkUniform(name);
  57287. this._vectors2[name] = value;
  57288. return this;
  57289. };
  57290. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57291. this._checkUniform(name);
  57292. this._vectors3[name] = value;
  57293. return this;
  57294. };
  57295. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57296. this._checkUniform(name);
  57297. this._vectors4[name] = value;
  57298. return this;
  57299. };
  57300. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57301. this._checkUniform(name);
  57302. this._matrices[name] = value;
  57303. return this;
  57304. };
  57305. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57306. this._checkUniform(name);
  57307. this._matrices3x3[name] = value;
  57308. return this;
  57309. };
  57310. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57311. this._checkUniform(name);
  57312. this._matrices2x2[name] = value;
  57313. return this;
  57314. };
  57315. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57316. this._checkUniform(name);
  57317. this._vectors2Arrays[name] = value;
  57318. return this;
  57319. };
  57320. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57321. this._checkUniform(name);
  57322. this._vectors3Arrays[name] = value;
  57323. return this;
  57324. };
  57325. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57326. if (!mesh) {
  57327. return true;
  57328. }
  57329. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57330. return false;
  57331. }
  57332. return false;
  57333. };
  57334. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57335. var scene = this.getScene();
  57336. var engine = scene.getEngine();
  57337. if (!this.checkReadyOnEveryCall) {
  57338. if (this._renderId === scene.getRenderId()) {
  57339. if (this._checkCache(scene, mesh, useInstances)) {
  57340. return true;
  57341. }
  57342. }
  57343. }
  57344. // Instances
  57345. var defines = [];
  57346. var attribs = [];
  57347. var fallbacks = new BABYLON.EffectFallbacks();
  57348. if (useInstances) {
  57349. defines.push("#define INSTANCES");
  57350. }
  57351. for (var index = 0; index < this._options.defines.length; index++) {
  57352. defines.push(this._options.defines[index]);
  57353. }
  57354. for (var index = 0; index < this._options.attributes.length; index++) {
  57355. attribs.push(this._options.attributes[index]);
  57356. }
  57357. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57358. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57359. defines.push("#define VERTEXCOLOR");
  57360. }
  57361. // Bones
  57362. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57365. if (mesh.numBoneInfluencers > 4) {
  57366. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57367. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57368. }
  57369. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57370. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57371. fallbacks.addCPUSkinningFallback(0, mesh);
  57372. if (this._options.uniforms.indexOf("mBones") === -1) {
  57373. this._options.uniforms.push("mBones");
  57374. }
  57375. }
  57376. else {
  57377. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57378. }
  57379. // Textures
  57380. for (var name in this._textures) {
  57381. if (!this._textures[name].isReady()) {
  57382. return false;
  57383. }
  57384. }
  57385. // Alpha test
  57386. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57387. defines.push("#define ALPHATEST");
  57388. }
  57389. var previousEffect = this._effect;
  57390. var join = defines.join("\n");
  57391. this._effect = engine.createEffect(this._shaderPath, {
  57392. attributes: attribs,
  57393. uniformsNames: this._options.uniforms,
  57394. uniformBuffersNames: this._options.uniformBuffers,
  57395. samplers: this._options.samplers,
  57396. defines: join,
  57397. fallbacks: fallbacks,
  57398. onCompiled: this.onCompiled,
  57399. onError: this.onError
  57400. }, engine);
  57401. if (!this._effect.isReady()) {
  57402. return false;
  57403. }
  57404. if (previousEffect !== this._effect) {
  57405. scene.resetCachedMaterial();
  57406. }
  57407. this._renderId = scene.getRenderId();
  57408. return true;
  57409. };
  57410. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57411. var scene = this.getScene();
  57412. if (!this._effect) {
  57413. return;
  57414. }
  57415. if (this._options.uniforms.indexOf("world") !== -1) {
  57416. this._effect.setMatrix("world", world);
  57417. }
  57418. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57419. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57420. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57421. }
  57422. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57423. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57424. }
  57425. };
  57426. ShaderMaterial.prototype.bind = function (world, mesh) {
  57427. // Std values
  57428. this.bindOnlyWorldMatrix(world);
  57429. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57430. if (this._options.uniforms.indexOf("view") !== -1) {
  57431. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57432. }
  57433. if (this._options.uniforms.indexOf("projection") !== -1) {
  57434. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57435. }
  57436. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57437. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57438. }
  57439. // Bones
  57440. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57441. var name;
  57442. // Texture
  57443. for (name in this._textures) {
  57444. this._effect.setTexture(name, this._textures[name]);
  57445. }
  57446. // Texture arrays
  57447. for (name in this._textureArrays) {
  57448. this._effect.setTextureArray(name, this._textureArrays[name]);
  57449. }
  57450. // Int
  57451. for (name in this._ints) {
  57452. this._effect.setInt(name, this._ints[name]);
  57453. }
  57454. // Float
  57455. for (name in this._floats) {
  57456. this._effect.setFloat(name, this._floats[name]);
  57457. }
  57458. // Floats
  57459. for (name in this._floatsArrays) {
  57460. this._effect.setArray(name, this._floatsArrays[name]);
  57461. }
  57462. // Color3
  57463. for (name in this._colors3) {
  57464. this._effect.setColor3(name, this._colors3[name]);
  57465. }
  57466. for (name in this._colors3Arrays) {
  57467. this._effect.setArray3(name, this._colors3Arrays[name]);
  57468. }
  57469. // Color4
  57470. for (name in this._colors4) {
  57471. var color = this._colors4[name];
  57472. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57473. }
  57474. // Vector2
  57475. for (name in this._vectors2) {
  57476. this._effect.setVector2(name, this._vectors2[name]);
  57477. }
  57478. // Vector3
  57479. for (name in this._vectors3) {
  57480. this._effect.setVector3(name, this._vectors3[name]);
  57481. }
  57482. // Vector4
  57483. for (name in this._vectors4) {
  57484. this._effect.setVector4(name, this._vectors4[name]);
  57485. }
  57486. // Matrix
  57487. for (name in this._matrices) {
  57488. this._effect.setMatrix(name, this._matrices[name]);
  57489. }
  57490. // Matrix 3x3
  57491. for (name in this._matrices3x3) {
  57492. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57493. }
  57494. // Matrix 2x2
  57495. for (name in this._matrices2x2) {
  57496. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57497. }
  57498. // Vector2Array
  57499. for (name in this._vectors2Arrays) {
  57500. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57501. }
  57502. // Vector3Array
  57503. for (name in this._vectors3Arrays) {
  57504. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57505. }
  57506. }
  57507. this._afterBind(mesh);
  57508. };
  57509. ShaderMaterial.prototype.getActiveTextures = function () {
  57510. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57511. for (var name in this._textures) {
  57512. activeTextures.push(this._textures[name]);
  57513. }
  57514. for (var name in this._textureArrays) {
  57515. var array = this._textureArrays[name];
  57516. for (var index = 0; index < array.length; index++) {
  57517. activeTextures.push(array[index]);
  57518. }
  57519. }
  57520. return activeTextures;
  57521. };
  57522. ShaderMaterial.prototype.hasTexture = function (texture) {
  57523. if (_super.prototype.hasTexture.call(this, texture)) {
  57524. return true;
  57525. }
  57526. for (var name in this._textures) {
  57527. if (this._textures[name] === texture) {
  57528. return true;
  57529. }
  57530. }
  57531. for (var name in this._textureArrays) {
  57532. var array = this._textureArrays[name];
  57533. for (var index = 0; index < array.length; index++) {
  57534. if (array[index] === texture) {
  57535. return true;
  57536. }
  57537. }
  57538. }
  57539. return false;
  57540. };
  57541. ShaderMaterial.prototype.clone = function (name) {
  57542. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57543. return newShaderMaterial;
  57544. };
  57545. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57546. if (forceDisposeTextures) {
  57547. var name;
  57548. for (name in this._textures) {
  57549. this._textures[name].dispose();
  57550. }
  57551. for (name in this._textureArrays) {
  57552. var array = this._textureArrays[name];
  57553. for (var index = 0; index < array.length; index++) {
  57554. array[index].dispose();
  57555. }
  57556. }
  57557. }
  57558. this._textures = {};
  57559. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57560. };
  57561. ShaderMaterial.prototype.serialize = function () {
  57562. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57563. serializationObject.customType = "BABYLON.ShaderMaterial";
  57564. serializationObject.options = this._options;
  57565. serializationObject.shaderPath = this._shaderPath;
  57566. var name;
  57567. // Texture
  57568. serializationObject.textures = {};
  57569. for (name in this._textures) {
  57570. serializationObject.textures[name] = this._textures[name].serialize();
  57571. }
  57572. // Texture arrays
  57573. serializationObject.textureArrays = {};
  57574. for (name in this._textureArrays) {
  57575. serializationObject.textureArrays[name] = [];
  57576. var array = this._textureArrays[name];
  57577. for (var index = 0; index < array.length; index++) {
  57578. serializationObject.textureArrays[name].push(array[index].serialize());
  57579. }
  57580. }
  57581. // Float
  57582. serializationObject.floats = {};
  57583. for (name in this._floats) {
  57584. serializationObject.floats[name] = this._floats[name];
  57585. }
  57586. // Float s
  57587. serializationObject.FloatArrays = {};
  57588. for (name in this._floatsArrays) {
  57589. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57590. }
  57591. // Color3
  57592. serializationObject.colors3 = {};
  57593. for (name in this._colors3) {
  57594. serializationObject.colors3[name] = this._colors3[name].asArray();
  57595. }
  57596. // Color3 array
  57597. serializationObject.colors3Arrays = {};
  57598. for (name in this._colors3Arrays) {
  57599. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57600. }
  57601. // Color4
  57602. serializationObject.colors4 = {};
  57603. for (name in this._colors4) {
  57604. serializationObject.colors4[name] = this._colors4[name].asArray();
  57605. }
  57606. // Vector2
  57607. serializationObject.vectors2 = {};
  57608. for (name in this._vectors2) {
  57609. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57610. }
  57611. // Vector3
  57612. serializationObject.vectors3 = {};
  57613. for (name in this._vectors3) {
  57614. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57615. }
  57616. // Vector4
  57617. serializationObject.vectors4 = {};
  57618. for (name in this._vectors4) {
  57619. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57620. }
  57621. // Matrix
  57622. serializationObject.matrices = {};
  57623. for (name in this._matrices) {
  57624. serializationObject.matrices[name] = this._matrices[name].asArray();
  57625. }
  57626. // Matrix 3x3
  57627. serializationObject.matrices3x3 = {};
  57628. for (name in this._matrices3x3) {
  57629. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57630. }
  57631. // Matrix 2x2
  57632. serializationObject.matrices2x2 = {};
  57633. for (name in this._matrices2x2) {
  57634. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57635. }
  57636. // Vector2Array
  57637. serializationObject.vectors2Arrays = {};
  57638. for (name in this._vectors2Arrays) {
  57639. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57640. }
  57641. // Vector3Array
  57642. serializationObject.vectors3Arrays = {};
  57643. for (name in this._vectors3Arrays) {
  57644. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57645. }
  57646. return serializationObject;
  57647. };
  57648. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57649. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57650. var name;
  57651. // Texture
  57652. for (name in source.textures) {
  57653. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57654. }
  57655. // Texture arrays
  57656. for (name in source.textureArrays) {
  57657. var array = source.textureArrays[name];
  57658. var textureArray = new Array();
  57659. for (var index = 0; index < array.length; index++) {
  57660. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  57661. }
  57662. material.setTextureArray(name, textureArray);
  57663. }
  57664. // Float
  57665. for (name in source.floats) {
  57666. material.setFloat(name, source.floats[name]);
  57667. }
  57668. // Float s
  57669. for (name in source.floatsArrays) {
  57670. material.setFloats(name, source.floatsArrays[name]);
  57671. }
  57672. // Color3
  57673. for (name in source.colors3) {
  57674. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  57675. }
  57676. // Color3 arrays
  57677. for (name in source.colors3Arrays) {
  57678. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  57679. if (i % 3 === 0) {
  57680. arr.push([num]);
  57681. }
  57682. else {
  57683. arr[arr.length - 1].push(num);
  57684. }
  57685. return arr;
  57686. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  57687. material.setColor3Array(name, colors);
  57688. }
  57689. // Color4
  57690. for (name in source.colors4) {
  57691. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  57692. }
  57693. // Vector2
  57694. for (name in source.vectors2) {
  57695. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  57696. }
  57697. // Vector3
  57698. for (name in source.vectors3) {
  57699. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  57700. }
  57701. // Vector4
  57702. for (name in source.vectors4) {
  57703. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  57704. }
  57705. // Matrix
  57706. for (name in source.matrices) {
  57707. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  57708. }
  57709. // Matrix 3x3
  57710. for (name in source.matrices3x3) {
  57711. material.setMatrix3x3(name, source.matrices3x3[name]);
  57712. }
  57713. // Matrix 2x2
  57714. for (name in source.matrices2x2) {
  57715. material.setMatrix2x2(name, source.matrices2x2[name]);
  57716. }
  57717. // Vector2Array
  57718. for (name in source.vectors2Arrays) {
  57719. material.setArray2(name, source.vectors2Arrays[name]);
  57720. }
  57721. // Vector3Array
  57722. for (name in source.vectors3Arrays) {
  57723. material.setArray3(name, source.vectors3Arrays[name]);
  57724. }
  57725. return material;
  57726. };
  57727. return ShaderMaterial;
  57728. }(BABYLON.Material));
  57729. BABYLON.ShaderMaterial = ShaderMaterial;
  57730. })(BABYLON || (BABYLON = {}));
  57731. //# sourceMappingURL=babylon.shaderMaterial.js.map
  57732. var BABYLON;
  57733. (function (BABYLON) {
  57734. var GroundMesh = /** @class */ (function (_super) {
  57735. __extends(GroundMesh, _super);
  57736. function GroundMesh(name, scene) {
  57737. var _this = _super.call(this, name, scene) || this;
  57738. _this.generateOctree = false;
  57739. return _this;
  57740. }
  57741. GroundMesh.prototype.getClassName = function () {
  57742. return "GroundMesh";
  57743. };
  57744. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  57745. get: function () {
  57746. return Math.min(this._subdivisionsX, this._subdivisionsY);
  57747. },
  57748. enumerable: true,
  57749. configurable: true
  57750. });
  57751. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  57752. get: function () {
  57753. return this._subdivisionsX;
  57754. },
  57755. enumerable: true,
  57756. configurable: true
  57757. });
  57758. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  57759. get: function () {
  57760. return this._subdivisionsY;
  57761. },
  57762. enumerable: true,
  57763. configurable: true
  57764. });
  57765. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  57766. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  57767. this._subdivisionsX = chunksCount;
  57768. this._subdivisionsY = chunksCount;
  57769. this.subdivide(chunksCount);
  57770. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  57771. };
  57772. /**
  57773. * Returns a height (y) value in the Worl system :
  57774. * the ground altitude at the coordinates (x, z) expressed in the World system.
  57775. * Returns the ground y position if (x, z) are outside the ground surface.
  57776. */
  57777. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  57778. var world = this.getWorldMatrix();
  57779. var invMat = BABYLON.Tmp.Matrix[5];
  57780. world.invertToRef(invMat);
  57781. var tmpVect = BABYLON.Tmp.Vector3[8];
  57782. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  57783. x = tmpVect.x;
  57784. z = tmpVect.z;
  57785. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57786. return this.position.y;
  57787. }
  57788. if (!this._heightQuads || this._heightQuads.length == 0) {
  57789. this._initHeightQuads();
  57790. this._computeHeightQuads();
  57791. }
  57792. var facet = this._getFacetAt(x, z);
  57793. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  57794. // return y in the World system
  57795. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  57796. return tmpVect.y;
  57797. };
  57798. /**
  57799. * Returns a normalized vector (Vector3) orthogonal to the ground
  57800. * at the ground coordinates (x, z) expressed in the World system.
  57801. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  57802. */
  57803. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  57804. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  57805. this.getNormalAtCoordinatesToRef(x, z, normal);
  57806. return normal;
  57807. };
  57808. /**
  57809. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  57810. * at the ground coordinates (x, z) expressed in the World system.
  57811. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  57812. * Returns the GroundMesh.
  57813. */
  57814. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  57815. var world = this.getWorldMatrix();
  57816. var tmpMat = BABYLON.Tmp.Matrix[5];
  57817. world.invertToRef(tmpMat);
  57818. var tmpVect = BABYLON.Tmp.Vector3[8];
  57819. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  57820. x = tmpVect.x;
  57821. z = tmpVect.z;
  57822. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57823. return this;
  57824. }
  57825. if (!this._heightQuads || this._heightQuads.length == 0) {
  57826. this._initHeightQuads();
  57827. this._computeHeightQuads();
  57828. }
  57829. var facet = this._getFacetAt(x, z);
  57830. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  57831. return this;
  57832. };
  57833. /**
  57834. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  57835. * if the ground has been updated.
  57836. * This can be used in the render loop.
  57837. * Returns the GroundMesh.
  57838. */
  57839. GroundMesh.prototype.updateCoordinateHeights = function () {
  57840. if (!this._heightQuads || this._heightQuads.length == 0) {
  57841. this._initHeightQuads();
  57842. }
  57843. this._computeHeightQuads();
  57844. return this;
  57845. };
  57846. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  57847. GroundMesh.prototype._getFacetAt = function (x, z) {
  57848. // retrieve col and row from x, z coordinates in the ground local system
  57849. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  57850. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  57851. var quad = this._heightQuads[row * this._subdivisionsX + col];
  57852. var facet;
  57853. if (z < quad.slope.x * x + quad.slope.y) {
  57854. facet = quad.facet1;
  57855. }
  57856. else {
  57857. facet = quad.facet2;
  57858. }
  57859. return facet;
  57860. };
  57861. // Creates and populates the heightMap array with "facet" elements :
  57862. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  57863. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57864. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57865. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57866. // Returns the GroundMesh.
  57867. GroundMesh.prototype._initHeightQuads = function () {
  57868. var subdivisionsX = this._subdivisionsX;
  57869. var subdivisionsY = this._subdivisionsY;
  57870. this._heightQuads = new Array();
  57871. for (var row = 0; row < subdivisionsY; row++) {
  57872. for (var col = 0; col < subdivisionsX; col++) {
  57873. 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) };
  57874. this._heightQuads[row * subdivisionsX + col] = quad;
  57875. }
  57876. }
  57877. return this;
  57878. };
  57879. // Compute each quad element values and update the the heightMap array :
  57880. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57881. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57882. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57883. // Returns the GroundMesh.
  57884. GroundMesh.prototype._computeHeightQuads = function () {
  57885. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57886. if (!positions) {
  57887. return this;
  57888. }
  57889. var v1 = BABYLON.Tmp.Vector3[3];
  57890. var v2 = BABYLON.Tmp.Vector3[2];
  57891. var v3 = BABYLON.Tmp.Vector3[1];
  57892. var v4 = BABYLON.Tmp.Vector3[0];
  57893. var v1v2 = BABYLON.Tmp.Vector3[4];
  57894. var v1v3 = BABYLON.Tmp.Vector3[5];
  57895. var v1v4 = BABYLON.Tmp.Vector3[6];
  57896. var norm1 = BABYLON.Tmp.Vector3[7];
  57897. var norm2 = BABYLON.Tmp.Vector3[8];
  57898. var i = 0;
  57899. var j = 0;
  57900. var k = 0;
  57901. var cd = 0; // 2D slope coefficient : z = cd * x + h
  57902. var h = 0;
  57903. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  57904. var d2 = 0;
  57905. var subdivisionsX = this._subdivisionsX;
  57906. var subdivisionsY = this._subdivisionsY;
  57907. for (var row = 0; row < subdivisionsY; row++) {
  57908. for (var col = 0; col < subdivisionsX; col++) {
  57909. i = col * 3;
  57910. j = row * (subdivisionsX + 1) * 3;
  57911. k = (row + 1) * (subdivisionsX + 1) * 3;
  57912. v1.x = positions[j + i];
  57913. v1.y = positions[j + i + 1];
  57914. v1.z = positions[j + i + 2];
  57915. v2.x = positions[j + i + 3];
  57916. v2.y = positions[j + i + 4];
  57917. v2.z = positions[j + i + 5];
  57918. v3.x = positions[k + i];
  57919. v3.y = positions[k + i + 1];
  57920. v3.z = positions[k + i + 2];
  57921. v4.x = positions[k + i + 3];
  57922. v4.y = positions[k + i + 4];
  57923. v4.z = positions[k + i + 5];
  57924. // 2D slope V1V4
  57925. cd = (v4.z - v1.z) / (v4.x - v1.x);
  57926. h = v1.z - cd * v1.x; // v1 belongs to the slope
  57927. // facet equations :
  57928. // we compute each facet normal vector
  57929. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  57930. // we compute the value d by applying the equation to v1 which belongs to the plane
  57931. // then we store the facet equation in a Vector4
  57932. v2.subtractToRef(v1, v1v2);
  57933. v3.subtractToRef(v1, v1v3);
  57934. v4.subtractToRef(v1, v1v4);
  57935. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  57936. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  57937. norm1.normalize();
  57938. norm2.normalize();
  57939. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  57940. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  57941. var quad = this._heightQuads[row * subdivisionsX + col];
  57942. quad.slope.copyFromFloats(cd, h);
  57943. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  57944. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  57945. }
  57946. }
  57947. return this;
  57948. };
  57949. GroundMesh.prototype.serialize = function (serializationObject) {
  57950. _super.prototype.serialize.call(this, serializationObject);
  57951. serializationObject.subdivisionsX = this._subdivisionsX;
  57952. serializationObject.subdivisionsY = this._subdivisionsY;
  57953. serializationObject.minX = this._minX;
  57954. serializationObject.maxX = this._maxX;
  57955. serializationObject.minZ = this._minZ;
  57956. serializationObject.maxZ = this._maxZ;
  57957. serializationObject.width = this._width;
  57958. serializationObject.height = this._height;
  57959. };
  57960. GroundMesh.Parse = function (parsedMesh, scene) {
  57961. var result = new GroundMesh(parsedMesh.name, scene);
  57962. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  57963. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  57964. result._minX = parsedMesh.minX;
  57965. result._maxX = parsedMesh.maxX;
  57966. result._minZ = parsedMesh.minZ;
  57967. result._maxZ = parsedMesh.maxZ;
  57968. result._width = parsedMesh.width;
  57969. result._height = parsedMesh.height;
  57970. return result;
  57971. };
  57972. return GroundMesh;
  57973. }(BABYLON.Mesh));
  57974. BABYLON.GroundMesh = GroundMesh;
  57975. })(BABYLON || (BABYLON = {}));
  57976. //# sourceMappingURL=babylon.groundMesh.js.map
  57977. var BABYLON;
  57978. (function (BABYLON) {
  57979. /**
  57980. * Creates an instance based on a source mesh.
  57981. */
  57982. var InstancedMesh = /** @class */ (function (_super) {
  57983. __extends(InstancedMesh, _super);
  57984. function InstancedMesh(name, source) {
  57985. var _this = _super.call(this, name, source.getScene()) || this;
  57986. source.instances.push(_this);
  57987. _this._sourceMesh = source;
  57988. _this.position.copyFrom(source.position);
  57989. _this.rotation.copyFrom(source.rotation);
  57990. _this.scaling.copyFrom(source.scaling);
  57991. if (source.rotationQuaternion) {
  57992. _this.rotationQuaternion = source.rotationQuaternion.clone();
  57993. }
  57994. _this.infiniteDistance = source.infiniteDistance;
  57995. _this.setPivotMatrix(source.getPivotMatrix());
  57996. _this.refreshBoundingInfo();
  57997. _this._syncSubMeshes();
  57998. return _this;
  57999. }
  58000. /**
  58001. * Returns the string "InstancedMesh".
  58002. */
  58003. InstancedMesh.prototype.getClassName = function () {
  58004. return "InstancedMesh";
  58005. };
  58006. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58007. // Methods
  58008. get: function () {
  58009. return this._sourceMesh.receiveShadows;
  58010. },
  58011. enumerable: true,
  58012. configurable: true
  58013. });
  58014. Object.defineProperty(InstancedMesh.prototype, "material", {
  58015. get: function () {
  58016. return this._sourceMesh.material;
  58017. },
  58018. enumerable: true,
  58019. configurable: true
  58020. });
  58021. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58022. get: function () {
  58023. return this._sourceMesh.visibility;
  58024. },
  58025. enumerable: true,
  58026. configurable: true
  58027. });
  58028. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58029. get: function () {
  58030. return this._sourceMesh.skeleton;
  58031. },
  58032. enumerable: true,
  58033. configurable: true
  58034. });
  58035. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58036. get: function () {
  58037. return this._sourceMesh.renderingGroupId;
  58038. },
  58039. set: function (value) {
  58040. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58041. return;
  58042. }
  58043. //no-op with warning
  58044. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58045. },
  58046. enumerable: true,
  58047. configurable: true
  58048. });
  58049. /**
  58050. * Returns the total number of vertices (integer).
  58051. */
  58052. InstancedMesh.prototype.getTotalVertices = function () {
  58053. return this._sourceMesh.getTotalVertices();
  58054. };
  58055. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58056. get: function () {
  58057. return this._sourceMesh;
  58058. },
  58059. enumerable: true,
  58060. configurable: true
  58061. });
  58062. /**
  58063. * Is this node ready to be used/rendered
  58064. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58065. * @return {boolean} is it ready
  58066. */
  58067. InstancedMesh.prototype.isReady = function (completeCheck) {
  58068. if (completeCheck === void 0) { completeCheck = false; }
  58069. return this._sourceMesh.isReady(completeCheck, true);
  58070. };
  58071. /**
  58072. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58073. */
  58074. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58075. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58076. };
  58077. /**
  58078. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58079. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58080. * The `data` are either a numeric array either a Float32Array.
  58081. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58082. * 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).
  58083. * Note that a new underlying VertexBuffer object is created each call.
  58084. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58085. *
  58086. * Possible `kind` values :
  58087. * - BABYLON.VertexBuffer.PositionKind
  58088. * - BABYLON.VertexBuffer.UVKind
  58089. * - BABYLON.VertexBuffer.UV2Kind
  58090. * - BABYLON.VertexBuffer.UV3Kind
  58091. * - BABYLON.VertexBuffer.UV4Kind
  58092. * - BABYLON.VertexBuffer.UV5Kind
  58093. * - BABYLON.VertexBuffer.UV6Kind
  58094. * - BABYLON.VertexBuffer.ColorKind
  58095. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58096. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58097. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58098. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58099. *
  58100. * Returns the Mesh.
  58101. */
  58102. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58103. if (this.sourceMesh) {
  58104. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58105. }
  58106. return this.sourceMesh;
  58107. };
  58108. /**
  58109. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58110. * If the mesh has no geometry, it is simply returned as it is.
  58111. * The `data` are either a numeric array either a Float32Array.
  58112. * No new underlying VertexBuffer object is created.
  58113. * 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.
  58114. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58115. *
  58116. * Possible `kind` values :
  58117. * - BABYLON.VertexBuffer.PositionKind
  58118. * - BABYLON.VertexBuffer.UVKind
  58119. * - BABYLON.VertexBuffer.UV2Kind
  58120. * - BABYLON.VertexBuffer.UV3Kind
  58121. * - BABYLON.VertexBuffer.UV4Kind
  58122. * - BABYLON.VertexBuffer.UV5Kind
  58123. * - BABYLON.VertexBuffer.UV6Kind
  58124. * - BABYLON.VertexBuffer.ColorKind
  58125. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58126. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58127. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58128. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58129. *
  58130. * Returns the Mesh.
  58131. */
  58132. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58133. if (this.sourceMesh) {
  58134. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58135. }
  58136. return this.sourceMesh;
  58137. };
  58138. /**
  58139. * Sets the mesh indices.
  58140. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58141. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58142. * This method creates a new index buffer each call.
  58143. * Returns the Mesh.
  58144. */
  58145. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58146. if (totalVertices === void 0) { totalVertices = null; }
  58147. if (this.sourceMesh) {
  58148. this.sourceMesh.setIndices(indices, totalVertices);
  58149. }
  58150. return this.sourceMesh;
  58151. };
  58152. /**
  58153. * Boolean : True if the mesh owns the requested kind of data.
  58154. */
  58155. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58156. return this._sourceMesh.isVerticesDataPresent(kind);
  58157. };
  58158. /**
  58159. * Returns an array of indices (IndicesArray).
  58160. */
  58161. InstancedMesh.prototype.getIndices = function () {
  58162. return this._sourceMesh.getIndices();
  58163. };
  58164. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58165. get: function () {
  58166. return this._sourceMesh._positions;
  58167. },
  58168. enumerable: true,
  58169. configurable: true
  58170. });
  58171. /**
  58172. * Sets a new updated BoundingInfo to the mesh.
  58173. * Returns the mesh.
  58174. */
  58175. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58176. var meshBB = this._sourceMesh.getBoundingInfo();
  58177. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58178. this._updateBoundingInfo();
  58179. return this;
  58180. };
  58181. InstancedMesh.prototype._preActivate = function () {
  58182. if (this._currentLOD) {
  58183. this._currentLOD._preActivate();
  58184. }
  58185. return this;
  58186. };
  58187. InstancedMesh.prototype._activate = function (renderId) {
  58188. if (this._currentLOD) {
  58189. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58190. }
  58191. return this;
  58192. };
  58193. /**
  58194. * Returns the current associated LOD AbstractMesh.
  58195. */
  58196. InstancedMesh.prototype.getLOD = function (camera) {
  58197. if (!camera) {
  58198. return this;
  58199. }
  58200. var boundingInfo = this.getBoundingInfo();
  58201. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58202. if (this._currentLOD === this.sourceMesh) {
  58203. return this;
  58204. }
  58205. return this._currentLOD;
  58206. };
  58207. InstancedMesh.prototype._syncSubMeshes = function () {
  58208. this.releaseSubMeshes();
  58209. if (this._sourceMesh.subMeshes) {
  58210. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58211. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58212. }
  58213. }
  58214. return this;
  58215. };
  58216. InstancedMesh.prototype._generatePointsArray = function () {
  58217. return this._sourceMesh._generatePointsArray();
  58218. };
  58219. /**
  58220. * Creates a new InstancedMesh from the current mesh.
  58221. * - name (string) : the cloned mesh name
  58222. * - newParent (optional Node) : the optional Node to parent the clone to.
  58223. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58224. *
  58225. * Returns the clone.
  58226. */
  58227. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58228. var result = this._sourceMesh.createInstance(name);
  58229. // Deep copy
  58230. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58231. // Bounding info
  58232. this.refreshBoundingInfo();
  58233. // Parent
  58234. if (newParent) {
  58235. result.parent = newParent;
  58236. }
  58237. if (!doNotCloneChildren) {
  58238. // Children
  58239. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58240. var mesh = this.getScene().meshes[index];
  58241. if (mesh.parent === this) {
  58242. mesh.clone(mesh.name, result);
  58243. }
  58244. }
  58245. }
  58246. result.computeWorldMatrix(true);
  58247. return result;
  58248. };
  58249. /**
  58250. * Disposes the InstancedMesh.
  58251. * Returns nothing.
  58252. */
  58253. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58254. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58255. // Remove from mesh
  58256. var index = this._sourceMesh.instances.indexOf(this);
  58257. this._sourceMesh.instances.splice(index, 1);
  58258. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58259. };
  58260. return InstancedMesh;
  58261. }(BABYLON.AbstractMesh));
  58262. BABYLON.InstancedMesh = InstancedMesh;
  58263. })(BABYLON || (BABYLON = {}));
  58264. //# sourceMappingURL=babylon.instancedMesh.js.map
  58265. var BABYLON;
  58266. (function (BABYLON) {
  58267. var LinesMesh = /** @class */ (function (_super) {
  58268. __extends(LinesMesh, _super);
  58269. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58270. if (scene === void 0) { scene = null; }
  58271. if (parent === void 0) { parent = null; }
  58272. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58273. _this.useVertexColor = useVertexColor;
  58274. _this.useVertexAlpha = useVertexAlpha;
  58275. _this.color = new BABYLON.Color3(1, 1, 1);
  58276. _this.alpha = 1;
  58277. if (source) {
  58278. _this.color = source.color.clone();
  58279. _this.alpha = source.alpha;
  58280. _this.useVertexColor = source.useVertexColor;
  58281. _this.useVertexAlpha = source.useVertexAlpha;
  58282. }
  58283. _this._intersectionThreshold = 0.1;
  58284. var defines = [];
  58285. var options = {
  58286. attributes: [BABYLON.VertexBuffer.PositionKind],
  58287. uniforms: ["world", "viewProjection"],
  58288. needAlphaBlending: true,
  58289. defines: defines
  58290. };
  58291. if (useVertexAlpha === false) {
  58292. options.needAlphaBlending = false;
  58293. }
  58294. if (!useVertexColor) {
  58295. options.uniforms.push("color");
  58296. }
  58297. else {
  58298. options.defines.push("#define VERTEXCOLOR");
  58299. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58300. }
  58301. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58302. return _this;
  58303. }
  58304. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58305. /**
  58306. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58307. * This margin is expressed in world space coordinates, so its value may vary.
  58308. * Default value is 0.1
  58309. * @returns the intersection Threshold value.
  58310. */
  58311. get: function () {
  58312. return this._intersectionThreshold;
  58313. },
  58314. /**
  58315. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58316. * This margin is expressed in world space coordinates, so its value may vary.
  58317. * @param value the new threshold to apply
  58318. */
  58319. set: function (value) {
  58320. if (this._intersectionThreshold === value) {
  58321. return;
  58322. }
  58323. this._intersectionThreshold = value;
  58324. if (this.geometry) {
  58325. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58326. }
  58327. },
  58328. enumerable: true,
  58329. configurable: true
  58330. });
  58331. /**
  58332. * Returns the string "LineMesh"
  58333. */
  58334. LinesMesh.prototype.getClassName = function () {
  58335. return "LinesMesh";
  58336. };
  58337. Object.defineProperty(LinesMesh.prototype, "material", {
  58338. /**
  58339. * @hidden
  58340. */
  58341. get: function () {
  58342. return this._colorShader;
  58343. },
  58344. /**
  58345. * @hidden
  58346. */
  58347. set: function (value) {
  58348. // Do nothing
  58349. },
  58350. enumerable: true,
  58351. configurable: true
  58352. });
  58353. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58354. /**
  58355. * @hidden
  58356. */
  58357. get: function () {
  58358. return false;
  58359. },
  58360. enumerable: true,
  58361. configurable: true
  58362. });
  58363. LinesMesh.prototype.createInstance = function (name) {
  58364. throw new Error("LinesMeshes do not support createInstance.");
  58365. };
  58366. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58367. if (!this._geometry) {
  58368. return this;
  58369. }
  58370. // VBOs
  58371. this._geometry._bind(this._colorShader.getEffect());
  58372. // Color
  58373. if (!this.useVertexColor) {
  58374. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58375. }
  58376. return this;
  58377. };
  58378. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58379. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58380. return this;
  58381. }
  58382. var engine = this.getScene().getEngine();
  58383. // Draw order
  58384. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58385. return this;
  58386. };
  58387. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58388. this._colorShader.dispose();
  58389. _super.prototype.dispose.call(this, doNotRecurse);
  58390. };
  58391. /**
  58392. * Returns a new LineMesh object cloned from the current one.
  58393. */
  58394. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58395. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58396. };
  58397. return LinesMesh;
  58398. }(BABYLON.Mesh));
  58399. BABYLON.LinesMesh = LinesMesh;
  58400. })(BABYLON || (BABYLON = {}));
  58401. //# sourceMappingURL=babylon.linesMesh.js.map
  58402. var BABYLON;
  58403. (function (BABYLON) {
  58404. /**
  58405. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58406. * The underlying implementation relies on an associative array to ensure the best performances.
  58407. * The value can be anything including 'null' but except 'undefined'
  58408. */
  58409. var StringDictionary = /** @class */ (function () {
  58410. function StringDictionary() {
  58411. this._count = 0;
  58412. this._data = {};
  58413. }
  58414. /**
  58415. * This will clear this dictionary and copy the content from the 'source' one.
  58416. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58417. * @param source the dictionary to take the content from and copy to this dictionary
  58418. */
  58419. StringDictionary.prototype.copyFrom = function (source) {
  58420. var _this = this;
  58421. this.clear();
  58422. source.forEach(function (t, v) { return _this.add(t, v); });
  58423. };
  58424. /**
  58425. * Get a value based from its key
  58426. * @param key the given key to get the matching value from
  58427. * @return the value if found, otherwise undefined is returned
  58428. */
  58429. StringDictionary.prototype.get = function (key) {
  58430. var val = this._data[key];
  58431. if (val !== undefined) {
  58432. return val;
  58433. }
  58434. return undefined;
  58435. };
  58436. /**
  58437. * Get a value from its key or add it if it doesn't exist.
  58438. * This method will ensure you that a given key/data will be present in the dictionary.
  58439. * @param key the given key to get the matching value from
  58440. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58441. * The factory will only be invoked if there's no data for the given key.
  58442. * @return the value corresponding to the key.
  58443. */
  58444. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58445. var val = this.get(key);
  58446. if (val !== undefined) {
  58447. return val;
  58448. }
  58449. val = factory(key);
  58450. if (val) {
  58451. this.add(key, val);
  58452. }
  58453. return val;
  58454. };
  58455. /**
  58456. * Get a value from its key if present in the dictionary otherwise add it
  58457. * @param key the key to get the value from
  58458. * @param val if there's no such key/value pair in the dictionary add it with this value
  58459. * @return the value corresponding to the key
  58460. */
  58461. StringDictionary.prototype.getOrAdd = function (key, val) {
  58462. var curVal = this.get(key);
  58463. if (curVal !== undefined) {
  58464. return curVal;
  58465. }
  58466. this.add(key, val);
  58467. return val;
  58468. };
  58469. /**
  58470. * Check if there's a given key in the dictionary
  58471. * @param key the key to check for
  58472. * @return true if the key is present, false otherwise
  58473. */
  58474. StringDictionary.prototype.contains = function (key) {
  58475. return this._data[key] !== undefined;
  58476. };
  58477. /**
  58478. * Add a new key and its corresponding value
  58479. * @param key the key to add
  58480. * @param value the value corresponding to the key
  58481. * @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
  58482. */
  58483. StringDictionary.prototype.add = function (key, value) {
  58484. if (this._data[key] !== undefined) {
  58485. return false;
  58486. }
  58487. this._data[key] = value;
  58488. ++this._count;
  58489. return true;
  58490. };
  58491. StringDictionary.prototype.set = function (key, value) {
  58492. if (this._data[key] === undefined) {
  58493. return false;
  58494. }
  58495. this._data[key] = value;
  58496. return true;
  58497. };
  58498. /**
  58499. * Get the element of the given key and remove it from the dictionary
  58500. * @param key
  58501. */
  58502. StringDictionary.prototype.getAndRemove = function (key) {
  58503. var val = this.get(key);
  58504. if (val !== undefined) {
  58505. delete this._data[key];
  58506. --this._count;
  58507. return val;
  58508. }
  58509. return null;
  58510. };
  58511. /**
  58512. * Remove a key/value from the dictionary.
  58513. * @param key the key to remove
  58514. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58515. */
  58516. StringDictionary.prototype.remove = function (key) {
  58517. if (this.contains(key)) {
  58518. delete this._data[key];
  58519. --this._count;
  58520. return true;
  58521. }
  58522. return false;
  58523. };
  58524. /**
  58525. * Clear the whole content of the dictionary
  58526. */
  58527. StringDictionary.prototype.clear = function () {
  58528. this._data = {};
  58529. this._count = 0;
  58530. };
  58531. Object.defineProperty(StringDictionary.prototype, "count", {
  58532. get: function () {
  58533. return this._count;
  58534. },
  58535. enumerable: true,
  58536. configurable: true
  58537. });
  58538. /**
  58539. * Execute a callback on each key/val of the dictionary.
  58540. * Note that you can remove any element in this dictionary in the callback implementation
  58541. * @param callback the callback to execute on a given key/value pair
  58542. */
  58543. StringDictionary.prototype.forEach = function (callback) {
  58544. for (var cur in this._data) {
  58545. var val = this._data[cur];
  58546. callback(cur, val);
  58547. }
  58548. };
  58549. /**
  58550. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58551. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58552. * Note that you can remove any element in this dictionary in the callback implementation
  58553. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58554. */
  58555. StringDictionary.prototype.first = function (callback) {
  58556. for (var cur in this._data) {
  58557. var val = this._data[cur];
  58558. var res = callback(cur, val);
  58559. if (res) {
  58560. return res;
  58561. }
  58562. }
  58563. return null;
  58564. };
  58565. return StringDictionary;
  58566. }());
  58567. BABYLON.StringDictionary = StringDictionary;
  58568. })(BABYLON || (BABYLON = {}));
  58569. //# sourceMappingURL=babylon.stringDictionary.js.map
  58570. var BABYLON;
  58571. (function (BABYLON) {
  58572. var Debug;
  58573. (function (Debug) {
  58574. /**
  58575. * Class used to render a debug view of a given skeleton
  58576. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  58577. */
  58578. var SkeletonViewer = /** @class */ (function () {
  58579. /**
  58580. * Creates a new SkeletonViewer
  58581. * @param skeleton defines the skeleton to render
  58582. * @param mesh defines the mesh attached to the skeleton
  58583. * @param scene defines the hosting scene
  58584. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  58585. * @param renderingGroupId defines the rendering group id to use with the viewer
  58586. */
  58587. function SkeletonViewer(
  58588. /** defines the skeleton to render */
  58589. skeleton,
  58590. /** defines the mesh attached to the skeleton */
  58591. mesh, scene,
  58592. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  58593. autoUpdateBonesMatrices,
  58594. /** defines the rendering group id to use with the viewer */
  58595. renderingGroupId) {
  58596. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58597. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58598. this.skeleton = skeleton;
  58599. this.mesh = mesh;
  58600. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58601. this.renderingGroupId = renderingGroupId;
  58602. /** Gets or sets the color used to render the skeleton */
  58603. this.color = BABYLON.Color3.White();
  58604. this._debugLines = new Array();
  58605. this._isEnabled = false;
  58606. this._scene = scene;
  58607. this.update();
  58608. this._renderFunction = this.update.bind(this);
  58609. }
  58610. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58611. get: function () {
  58612. return this._isEnabled;
  58613. },
  58614. /** Gets or sets a boolean indicating if the viewer is enabled */
  58615. set: function (value) {
  58616. if (this._isEnabled === value) {
  58617. return;
  58618. }
  58619. this._isEnabled = value;
  58620. if (value) {
  58621. this._scene.registerBeforeRender(this._renderFunction);
  58622. }
  58623. else {
  58624. this._scene.unregisterBeforeRender(this._renderFunction);
  58625. }
  58626. },
  58627. enumerable: true,
  58628. configurable: true
  58629. });
  58630. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58631. if (x === void 0) { x = 0; }
  58632. if (y === void 0) { y = 0; }
  58633. if (z === void 0) { z = 0; }
  58634. var tmat = BABYLON.Tmp.Matrix[0];
  58635. var parentBone = bone.getParent();
  58636. tmat.copyFrom(bone.getLocalMatrix());
  58637. if (x !== 0 || y !== 0 || z !== 0) {
  58638. var tmat2 = BABYLON.Tmp.Matrix[1];
  58639. BABYLON.Matrix.IdentityToRef(tmat2);
  58640. tmat2.m[12] = x;
  58641. tmat2.m[13] = y;
  58642. tmat2.m[14] = z;
  58643. tmat2.multiplyToRef(tmat, tmat);
  58644. }
  58645. if (parentBone) {
  58646. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58647. }
  58648. tmat.multiplyToRef(meshMat, tmat);
  58649. position.x = tmat.m[12];
  58650. position.y = tmat.m[13];
  58651. position.z = tmat.m[14];
  58652. };
  58653. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58654. var len = bones.length;
  58655. var meshPos = this.mesh.position;
  58656. for (var i = 0; i < len; i++) {
  58657. var bone = bones[i];
  58658. var points = this._debugLines[i];
  58659. if (!points) {
  58660. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58661. this._debugLines[i] = points;
  58662. }
  58663. this._getBonePosition(points[0], bone, meshMat);
  58664. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58665. points[0].subtractInPlace(meshPos);
  58666. points[1].subtractInPlace(meshPos);
  58667. }
  58668. };
  58669. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58670. var len = bones.length;
  58671. var boneNum = 0;
  58672. var meshPos = this.mesh.position;
  58673. for (var i = len - 1; i >= 0; i--) {
  58674. var childBone = bones[i];
  58675. var parentBone = childBone.getParent();
  58676. if (!parentBone) {
  58677. continue;
  58678. }
  58679. var points = this._debugLines[boneNum];
  58680. if (!points) {
  58681. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58682. this._debugLines[boneNum] = points;
  58683. }
  58684. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58685. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58686. points[0].subtractInPlace(meshPos);
  58687. points[1].subtractInPlace(meshPos);
  58688. boneNum++;
  58689. }
  58690. };
  58691. /** Update the viewer to sync with current skeleton state */
  58692. SkeletonViewer.prototype.update = function () {
  58693. if (this.autoUpdateBonesMatrices) {
  58694. this.skeleton.computeAbsoluteTransforms();
  58695. }
  58696. if (this.skeleton.bones[0].length === undefined) {
  58697. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58698. }
  58699. else {
  58700. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58701. }
  58702. if (!this._debugMesh) {
  58703. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  58704. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58705. }
  58706. else {
  58707. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58708. }
  58709. this._debugMesh.position.copyFrom(this.mesh.position);
  58710. this._debugMesh.color = this.color;
  58711. };
  58712. /** Release associated resources */
  58713. SkeletonViewer.prototype.dispose = function () {
  58714. if (this._debugMesh) {
  58715. this.isEnabled = false;
  58716. this._debugMesh.dispose();
  58717. this._debugMesh = null;
  58718. }
  58719. };
  58720. return SkeletonViewer;
  58721. }());
  58722. Debug.SkeletonViewer = SkeletonViewer;
  58723. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58724. })(BABYLON || (BABYLON = {}));
  58725. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58726. /**
  58727. * Module Debug contains the (visual) components to debug a scene correctly
  58728. */
  58729. var BABYLON;
  58730. (function (BABYLON) {
  58731. var Debug;
  58732. (function (Debug) {
  58733. /**
  58734. * The Axes viewer will show 3 axes in a specific point in space
  58735. */
  58736. var AxesViewer = /** @class */ (function () {
  58737. /**
  58738. * Creates a new AxesViewer
  58739. * @param scene defines the hosting scene
  58740. * @param scaleLines defines a number used to scale line length (1 by default)
  58741. */
  58742. function AxesViewer(scene, scaleLines) {
  58743. if (scaleLines === void 0) { scaleLines = 1; }
  58744. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58745. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58746. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58747. /**
  58748. * Gets or sets a number used to scale line length
  58749. */
  58750. this.scaleLines = 1;
  58751. this.scaleLines = scaleLines;
  58752. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  58753. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  58754. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  58755. this._xmesh.renderingGroupId = 2;
  58756. this._ymesh.renderingGroupId = 2;
  58757. this._zmesh.renderingGroupId = 2;
  58758. this._xmesh.material.checkReadyOnlyOnce = true;
  58759. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  58760. this._ymesh.material.checkReadyOnlyOnce = true;
  58761. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  58762. this._zmesh.material.checkReadyOnlyOnce = true;
  58763. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  58764. this.scene = scene;
  58765. }
  58766. /**
  58767. * Force the viewer to update
  58768. * @param position defines the position of the viewer
  58769. * @param xaxis defines the x axis of the viewer
  58770. * @param yaxis defines the y axis of the viewer
  58771. * @param zaxis defines the z axis of the viewer
  58772. */
  58773. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  58774. var scaleLines = this.scaleLines;
  58775. if (this._xmesh) {
  58776. this._xmesh.position.copyFrom(position);
  58777. }
  58778. if (this._ymesh) {
  58779. this._ymesh.position.copyFrom(position);
  58780. }
  58781. if (this._zmesh) {
  58782. this._zmesh.position.copyFrom(position);
  58783. }
  58784. var point2 = this._xline[1];
  58785. point2.x = xaxis.x * scaleLines;
  58786. point2.y = xaxis.y * scaleLines;
  58787. point2.z = xaxis.z * scaleLines;
  58788. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  58789. point2 = this._yline[1];
  58790. point2.x = yaxis.x * scaleLines;
  58791. point2.y = yaxis.y * scaleLines;
  58792. point2.z = yaxis.z * scaleLines;
  58793. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  58794. point2 = this._zline[1];
  58795. point2.x = zaxis.x * scaleLines;
  58796. point2.y = zaxis.y * scaleLines;
  58797. point2.z = zaxis.z * scaleLines;
  58798. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  58799. };
  58800. /** Releases resources */
  58801. AxesViewer.prototype.dispose = function () {
  58802. if (this._xmesh) {
  58803. this._xmesh.dispose();
  58804. }
  58805. if (this._ymesh) {
  58806. this._ymesh.dispose();
  58807. }
  58808. if (this._zmesh) {
  58809. this._zmesh.dispose();
  58810. }
  58811. this._xmesh = null;
  58812. this._ymesh = null;
  58813. this._zmesh = null;
  58814. this.scene = null;
  58815. };
  58816. return AxesViewer;
  58817. }());
  58818. Debug.AxesViewer = AxesViewer;
  58819. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58820. })(BABYLON || (BABYLON = {}));
  58821. //# sourceMappingURL=babylon.axesViewer.js.map
  58822. var BABYLON;
  58823. (function (BABYLON) {
  58824. var Debug;
  58825. (function (Debug) {
  58826. /**
  58827. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  58828. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  58829. */
  58830. var BoneAxesViewer = /** @class */ (function (_super) {
  58831. __extends(BoneAxesViewer, _super);
  58832. /**
  58833. * Creates a new BoneAxesViewer
  58834. * @param scene defines the hosting scene
  58835. * @param bone defines the target bone
  58836. * @param mesh defines the target mesh
  58837. * @param scaleLines defines a scaling factor for line length (1 by default)
  58838. */
  58839. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  58840. if (scaleLines === void 0) { scaleLines = 1; }
  58841. var _this = _super.call(this, scene, scaleLines) || this;
  58842. /** Gets current position */
  58843. _this.pos = BABYLON.Vector3.Zero();
  58844. /** Gets direction of X axis */
  58845. _this.xaxis = BABYLON.Vector3.Zero();
  58846. /** Gets direction of Y axis */
  58847. _this.yaxis = BABYLON.Vector3.Zero();
  58848. /** Gets direction of Z axis */
  58849. _this.zaxis = BABYLON.Vector3.Zero();
  58850. _this.mesh = mesh;
  58851. _this.bone = bone;
  58852. return _this;
  58853. }
  58854. /**
  58855. * Force the viewer to update
  58856. */
  58857. BoneAxesViewer.prototype.update = function () {
  58858. if (!this.mesh || !this.bone) {
  58859. return;
  58860. }
  58861. var bone = this.bone;
  58862. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  58863. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  58864. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  58865. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  58866. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  58867. };
  58868. /** Releases resources */
  58869. BoneAxesViewer.prototype.dispose = function () {
  58870. if (this.mesh) {
  58871. this.mesh = null;
  58872. this.bone = null;
  58873. _super.prototype.dispose.call(this);
  58874. }
  58875. };
  58876. return BoneAxesViewer;
  58877. }(Debug.AxesViewer));
  58878. Debug.BoneAxesViewer = BoneAxesViewer;
  58879. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58880. })(BABYLON || (BABYLON = {}));
  58881. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  58882. var BABYLON;
  58883. (function (BABYLON) {
  58884. var RayHelper = /** @class */ (function () {
  58885. function RayHelper(ray) {
  58886. this.ray = ray;
  58887. }
  58888. RayHelper.CreateAndShow = function (ray, scene, color) {
  58889. var helper = new RayHelper(ray);
  58890. helper.show(scene, color);
  58891. return helper;
  58892. };
  58893. RayHelper.prototype.show = function (scene, color) {
  58894. if (!this._renderFunction && this.ray) {
  58895. var ray = this.ray;
  58896. this._renderFunction = this._render.bind(this);
  58897. this._scene = scene;
  58898. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  58899. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  58900. if (this._renderFunction) {
  58901. this._scene.registerBeforeRender(this._renderFunction);
  58902. }
  58903. }
  58904. if (color && this._renderLine) {
  58905. this._renderLine.color.copyFrom(color);
  58906. }
  58907. };
  58908. RayHelper.prototype.hide = function () {
  58909. if (this._renderFunction && this._scene) {
  58910. this._scene.unregisterBeforeRender(this._renderFunction);
  58911. this._scene = null;
  58912. this._renderFunction = null;
  58913. if (this._renderLine) {
  58914. this._renderLine.dispose();
  58915. this._renderLine = null;
  58916. }
  58917. this._renderPoints = [];
  58918. }
  58919. };
  58920. RayHelper.prototype._render = function () {
  58921. var ray = this.ray;
  58922. if (!ray) {
  58923. return;
  58924. }
  58925. var point = this._renderPoints[1];
  58926. var len = Math.min(ray.length, 1000000);
  58927. point.copyFrom(ray.direction);
  58928. point.scaleInPlace(len);
  58929. point.addInPlace(ray.origin);
  58930. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  58931. };
  58932. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  58933. this._attachedToMesh = mesh;
  58934. var ray = this.ray;
  58935. if (!ray) {
  58936. return;
  58937. }
  58938. if (!ray.direction) {
  58939. ray.direction = BABYLON.Vector3.Zero();
  58940. }
  58941. if (!ray.origin) {
  58942. ray.origin = BABYLON.Vector3.Zero();
  58943. }
  58944. if (length) {
  58945. ray.length = length;
  58946. }
  58947. if (!meshSpaceOrigin) {
  58948. meshSpaceOrigin = BABYLON.Vector3.Zero();
  58949. }
  58950. if (!meshSpaceDirection) {
  58951. // -1 so that this will work with Mesh.lookAt
  58952. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  58953. }
  58954. if (!this._meshSpaceDirection) {
  58955. this._meshSpaceDirection = meshSpaceDirection.clone();
  58956. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  58957. }
  58958. else {
  58959. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  58960. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  58961. }
  58962. if (!this._updateToMeshFunction) {
  58963. this._updateToMeshFunction = this._updateToMesh.bind(this);
  58964. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  58965. }
  58966. this._updateToMesh();
  58967. };
  58968. RayHelper.prototype.detachFromMesh = function () {
  58969. if (this._attachedToMesh) {
  58970. if (this._updateToMeshFunction) {
  58971. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  58972. }
  58973. this._attachedToMesh = null;
  58974. this._updateToMeshFunction = null;
  58975. }
  58976. };
  58977. RayHelper.prototype._updateToMesh = function () {
  58978. var ray = this.ray;
  58979. if (!this._attachedToMesh || !ray) {
  58980. return;
  58981. }
  58982. if (this._attachedToMesh._isDisposed) {
  58983. this.detachFromMesh();
  58984. return;
  58985. }
  58986. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  58987. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  58988. };
  58989. RayHelper.prototype.dispose = function () {
  58990. this.hide();
  58991. this.detachFromMesh();
  58992. this.ray = null;
  58993. };
  58994. return RayHelper;
  58995. }());
  58996. BABYLON.RayHelper = RayHelper;
  58997. })(BABYLON || (BABYLON = {}));
  58998. //# sourceMappingURL=babylon.rayHelper.js.map
  58999. var BABYLON;
  59000. (function (BABYLON) {
  59001. // load the inspector using require, if not present in the global namespace.
  59002. var DebugLayer = /** @class */ (function () {
  59003. function DebugLayer(scene) {
  59004. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  59005. this.onPropertyChangedObservable = new BABYLON.Observable();
  59006. this._scene = scene;
  59007. }
  59008. /** Creates the inspector window. */
  59009. DebugLayer.prototype._createInspector = function (config) {
  59010. if (config === void 0) { config = {}; }
  59011. var popup = config.popup || false;
  59012. var initialTab = config.initialTab || 0;
  59013. var parentElement = config.parentElement || null;
  59014. if (!this._inspector) {
  59015. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  59016. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  59017. } // else nothing to do as instance is already created
  59018. };
  59019. DebugLayer.prototype.isVisible = function () {
  59020. if (!this._inspector) {
  59021. return false;
  59022. }
  59023. return true;
  59024. };
  59025. DebugLayer.prototype.hide = function () {
  59026. if (this._inspector) {
  59027. try {
  59028. this._inspector.dispose();
  59029. }
  59030. catch (e) {
  59031. // If the inspector has been removed directly from the inspector tool
  59032. }
  59033. this.onPropertyChangedObservable.clear();
  59034. this._inspector = null;
  59035. }
  59036. };
  59037. /**
  59038. *
  59039. * Launch the debugLayer.
  59040. *
  59041. * initialTab:
  59042. * | Value | Tab Name |
  59043. * | --- | --- |
  59044. * | 0 | Scene |
  59045. * | 1 | Console |
  59046. * | 2 | Stats |
  59047. * | 3 | Textures |
  59048. * | 4 | Mesh |
  59049. * | 5 | Light |
  59050. * | 6 | Material |
  59051. * | 7 | GLTF |
  59052. * | 8 | GUI |
  59053. * | 9 | Physics |
  59054. * | 10 | Camera |
  59055. * | 11 | Audio |
  59056. *
  59057. */
  59058. DebugLayer.prototype.show = function (config) {
  59059. if (config === void 0) { config = {}; }
  59060. if (typeof this.BJSINSPECTOR == 'undefined') {
  59061. // Load inspector and add it to the DOM
  59062. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59063. }
  59064. else {
  59065. // Otherwise creates the inspector
  59066. this._createInspector(config);
  59067. }
  59068. };
  59069. /**
  59070. * Gets the active tab
  59071. * @return the index of the active tab or -1 if the inspector is hidden
  59072. */
  59073. DebugLayer.prototype.getActiveTab = function () {
  59074. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  59075. };
  59076. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  59077. return DebugLayer;
  59078. }());
  59079. BABYLON.DebugLayer = DebugLayer;
  59080. })(BABYLON || (BABYLON = {}));
  59081. //# sourceMappingURL=babylon.debugLayer.js.map
  59082. var BABYLON;
  59083. (function (BABYLON) {
  59084. var Debug;
  59085. (function (Debug) {
  59086. /**
  59087. * Used to show the physics impostor around the specific mesh
  59088. */
  59089. var PhysicsViewer = /** @class */ (function () {
  59090. /**
  59091. * Creates a new PhysicsViewer
  59092. * @param scene defines the hosting scene
  59093. */
  59094. function PhysicsViewer(scene) {
  59095. /** @hidden */
  59096. this._impostors = [];
  59097. /** @hidden */
  59098. this._meshes = [];
  59099. /** @hidden */
  59100. this._numMeshes = 0;
  59101. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59102. var physicEngine = this._scene.getPhysicsEngine();
  59103. if (physicEngine) {
  59104. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  59105. }
  59106. }
  59107. /** @hidden */
  59108. PhysicsViewer.prototype._updateDebugMeshes = function () {
  59109. var plugin = this._physicsEnginePlugin;
  59110. for (var i = 0; i < this._numMeshes; i++) {
  59111. var impostor = this._impostors[i];
  59112. if (!impostor) {
  59113. continue;
  59114. }
  59115. if (impostor.isDisposed) {
  59116. this.hideImpostor(this._impostors[i--]);
  59117. }
  59118. else {
  59119. var mesh = this._meshes[i];
  59120. if (mesh && plugin) {
  59121. plugin.syncMeshWithImpostor(mesh, impostor);
  59122. }
  59123. }
  59124. }
  59125. };
  59126. /**
  59127. * Renders a specified physic impostor
  59128. * @param impostor defines the impostor to render
  59129. */
  59130. PhysicsViewer.prototype.showImpostor = function (impostor) {
  59131. if (!this._scene) {
  59132. return;
  59133. }
  59134. for (var i = 0; i < this._numMeshes; i++) {
  59135. if (this._impostors[i] == impostor) {
  59136. return;
  59137. }
  59138. }
  59139. var debugMesh = this._getDebugMesh(impostor, this._scene);
  59140. if (debugMesh) {
  59141. this._impostors[this._numMeshes] = impostor;
  59142. this._meshes[this._numMeshes] = debugMesh;
  59143. if (this._numMeshes === 0) {
  59144. this._renderFunction = this._updateDebugMeshes.bind(this);
  59145. this._scene.registerBeforeRender(this._renderFunction);
  59146. }
  59147. this._numMeshes++;
  59148. }
  59149. };
  59150. /**
  59151. * Hides a specified physic impostor
  59152. * @param impostor defines the impostor to hide
  59153. */
  59154. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  59155. if (!impostor || !this._scene) {
  59156. return;
  59157. }
  59158. var removed = false;
  59159. for (var i = 0; i < this._numMeshes; i++) {
  59160. if (this._impostors[i] == impostor) {
  59161. var mesh = this._meshes[i];
  59162. if (!mesh) {
  59163. continue;
  59164. }
  59165. this._scene.removeMesh(mesh);
  59166. mesh.dispose();
  59167. this._numMeshes--;
  59168. if (this._numMeshes > 0) {
  59169. this._meshes[i] = this._meshes[this._numMeshes];
  59170. this._impostors[i] = this._impostors[this._numMeshes];
  59171. this._meshes[this._numMeshes] = null;
  59172. this._impostors[this._numMeshes] = null;
  59173. }
  59174. else {
  59175. this._meshes[0] = null;
  59176. this._impostors[0] = null;
  59177. }
  59178. removed = true;
  59179. break;
  59180. }
  59181. }
  59182. if (removed && this._numMeshes === 0) {
  59183. this._scene.unregisterBeforeRender(this._renderFunction);
  59184. }
  59185. };
  59186. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  59187. if (!this._debugMaterial) {
  59188. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59189. this._debugMaterial.wireframe = true;
  59190. }
  59191. return this._debugMaterial;
  59192. };
  59193. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  59194. if (!this._debugBoxMesh) {
  59195. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59196. this._debugBoxMesh.renderingGroupId = 1;
  59197. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59198. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59199. scene.removeMesh(this._debugBoxMesh);
  59200. }
  59201. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59202. };
  59203. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  59204. if (!this._debugSphereMesh) {
  59205. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59206. this._debugSphereMesh.renderingGroupId = 1;
  59207. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59208. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59209. scene.removeMesh(this._debugSphereMesh);
  59210. }
  59211. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59212. };
  59213. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  59214. var mesh = null;
  59215. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  59216. mesh = this._getDebugBoxMesh(scene);
  59217. impostor.getBoxSizeToRef(mesh.scaling);
  59218. }
  59219. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  59220. mesh = this._getDebugSphereMesh(scene);
  59221. var radius = impostor.getRadius();
  59222. mesh.scaling.x = radius * 2;
  59223. mesh.scaling.y = radius * 2;
  59224. mesh.scaling.z = radius * 2;
  59225. }
  59226. return mesh;
  59227. };
  59228. /** Releases all resources */
  59229. PhysicsViewer.prototype.dispose = function () {
  59230. for (var i = 0; i < this._numMeshes; i++) {
  59231. this.hideImpostor(this._impostors[i]);
  59232. }
  59233. if (this._debugBoxMesh) {
  59234. this._debugBoxMesh.dispose();
  59235. }
  59236. if (this._debugSphereMesh) {
  59237. this._debugSphereMesh.dispose();
  59238. }
  59239. if (this._debugMaterial) {
  59240. this._debugMaterial.dispose();
  59241. }
  59242. this._impostors.length = 0;
  59243. this._scene = null;
  59244. this._physicsEnginePlugin = null;
  59245. };
  59246. return PhysicsViewer;
  59247. }());
  59248. Debug.PhysicsViewer = PhysicsViewer;
  59249. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59250. })(BABYLON || (BABYLON = {}));
  59251. //# sourceMappingURL=babylon.physicsViewer.js.map
  59252. var BABYLON;
  59253. (function (BABYLON) {
  59254. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  59255. get: function () {
  59256. return this._forceShowBoundingBoxes || false;
  59257. },
  59258. set: function (value) {
  59259. this._forceShowBoundingBoxes = value;
  59260. // Lazyly creates a BB renderer if needed.
  59261. if (value) {
  59262. this.getBoundingBoxRenderer();
  59263. }
  59264. },
  59265. enumerable: true,
  59266. configurable: true
  59267. });
  59268. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  59269. if (!this._boundingBoxRenderer) {
  59270. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  59271. }
  59272. return this._boundingBoxRenderer;
  59273. };
  59274. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  59275. get: function () {
  59276. return this._showBoundingBox || false;
  59277. },
  59278. set: function (value) {
  59279. this._showBoundingBox = value;
  59280. // Lazyly creates a BB renderer if needed.
  59281. if (value) {
  59282. this.getScene().getBoundingBoxRenderer();
  59283. }
  59284. },
  59285. enumerable: true,
  59286. configurable: true
  59287. });
  59288. var BoundingBoxRenderer = /** @class */ (function () {
  59289. function BoundingBoxRenderer(scene) {
  59290. /**
  59291. * The component name helpfull to identify the component in the list of scene components.
  59292. */
  59293. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  59294. this.frontColor = new BABYLON.Color3(1, 1, 1);
  59295. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  59296. this.showBackLines = true;
  59297. this.renderList = new BABYLON.SmartArray(32);
  59298. this._vertexBuffers = {};
  59299. this.scene = scene;
  59300. scene._addComponent(this);
  59301. }
  59302. /**
  59303. * Registers the component in a given scene
  59304. */
  59305. BoundingBoxRenderer.prototype.register = function () {
  59306. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  59307. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  59308. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  59309. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  59310. };
  59311. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  59312. if (mesh.showSubMeshesBoundingBox) {
  59313. var boundingInfo = subMesh.getBoundingInfo();
  59314. if (boundingInfo !== null && boundingInfo !== undefined) {
  59315. this.renderList.push(boundingInfo.boundingBox);
  59316. }
  59317. }
  59318. };
  59319. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  59320. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  59321. var boundingInfo = sourceMesh.getBoundingInfo();
  59322. this.renderList.push(boundingInfo.boundingBox);
  59323. }
  59324. };
  59325. BoundingBoxRenderer.prototype._prepareRessources = function () {
  59326. if (this._colorShader) {
  59327. return;
  59328. }
  59329. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  59330. attributes: [BABYLON.VertexBuffer.PositionKind],
  59331. uniforms: ["world", "viewProjection", "color"]
  59332. });
  59333. var engine = this.scene.getEngine();
  59334. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  59335. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  59336. this._createIndexBuffer();
  59337. };
  59338. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  59339. var engine = this.scene.getEngine();
  59340. 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]);
  59341. };
  59342. /**
  59343. * Rebuilds the elements related to this component in case of
  59344. * context lost for instance.
  59345. */
  59346. BoundingBoxRenderer.prototype.rebuild = function () {
  59347. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59348. if (vb) {
  59349. vb._rebuild();
  59350. }
  59351. this._createIndexBuffer();
  59352. };
  59353. BoundingBoxRenderer.prototype.reset = function () {
  59354. this.renderList.reset();
  59355. };
  59356. BoundingBoxRenderer.prototype.render = function () {
  59357. if (this.renderList.length === 0) {
  59358. return;
  59359. }
  59360. this._prepareRessources();
  59361. if (!this._colorShader.isReady()) {
  59362. return;
  59363. }
  59364. var engine = this.scene.getEngine();
  59365. engine.setDepthWrite(false);
  59366. this._colorShader._preBind();
  59367. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  59368. var boundingBox = this.renderList.data[boundingBoxIndex];
  59369. var min = boundingBox.minimum;
  59370. var max = boundingBox.maximum;
  59371. var diff = max.subtract(min);
  59372. var median = min.add(diff.scale(0.5));
  59373. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59374. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59375. .multiply(boundingBox.getWorldMatrix());
  59376. // VBOs
  59377. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59378. if (this.showBackLines) {
  59379. // Back
  59380. engine.setDepthFunctionToGreaterOrEqual();
  59381. this.scene.resetCachedMaterial();
  59382. this._colorShader.setColor4("color", this.backColor.toColor4());
  59383. this._colorShader.bind(worldMatrix);
  59384. // Draw order
  59385. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59386. }
  59387. // Front
  59388. engine.setDepthFunctionToLess();
  59389. this.scene.resetCachedMaterial();
  59390. this._colorShader.setColor4("color", this.frontColor.toColor4());
  59391. this._colorShader.bind(worldMatrix);
  59392. // Draw order
  59393. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59394. }
  59395. this._colorShader.unbind();
  59396. engine.setDepthFunctionToLessOrEqual();
  59397. engine.setDepthWrite(true);
  59398. };
  59399. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  59400. this._prepareRessources();
  59401. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  59402. return;
  59403. }
  59404. var engine = this.scene.getEngine();
  59405. engine.setDepthWrite(false);
  59406. engine.setColorWrite(false);
  59407. this._colorShader._preBind();
  59408. var boundingBox = mesh._boundingInfo.boundingBox;
  59409. var min = boundingBox.minimum;
  59410. var max = boundingBox.maximum;
  59411. var diff = max.subtract(min);
  59412. var median = min.add(diff.scale(0.5));
  59413. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59414. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59415. .multiply(boundingBox.getWorldMatrix());
  59416. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59417. engine.setDepthFunctionToLess();
  59418. this.scene.resetCachedMaterial();
  59419. this._colorShader.bind(worldMatrix);
  59420. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59421. this._colorShader.unbind();
  59422. engine.setDepthFunctionToLessOrEqual();
  59423. engine.setDepthWrite(true);
  59424. engine.setColorWrite(true);
  59425. };
  59426. BoundingBoxRenderer.prototype.dispose = function () {
  59427. if (!this._colorShader) {
  59428. return;
  59429. }
  59430. this.renderList.dispose();
  59431. this._colorShader.dispose();
  59432. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59433. if (buffer) {
  59434. buffer.dispose();
  59435. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59436. }
  59437. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  59438. };
  59439. return BoundingBoxRenderer;
  59440. }());
  59441. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  59442. })(BABYLON || (BABYLON = {}));
  59443. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  59444. var BABYLON;
  59445. (function (BABYLON) {
  59446. BABYLON.Engine.prototype.createTransformFeedback = function () {
  59447. return this._gl.createTransformFeedback();
  59448. };
  59449. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  59450. this._gl.deleteTransformFeedback(value);
  59451. };
  59452. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  59453. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  59454. };
  59455. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  59456. if (usePoints === void 0) { usePoints = true; }
  59457. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  59458. };
  59459. BABYLON.Engine.prototype.endTransformFeedback = function () {
  59460. this._gl.endTransformFeedback();
  59461. };
  59462. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  59463. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  59464. };
  59465. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  59466. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  59467. };
  59468. })(BABYLON || (BABYLON = {}));
  59469. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  59470. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59471. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59472. s = arguments[i];
  59473. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59474. t[p] = s[p];
  59475. }
  59476. return t;
  59477. };
  59478. var BABYLON;
  59479. (function (BABYLON) {
  59480. /**
  59481. * This represents a GPU particle system in Babylon
  59482. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  59483. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  59484. */
  59485. var GPUParticleSystem = /** @class */ (function () {
  59486. /**
  59487. * Instantiates a GPU particle system.
  59488. * 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.
  59489. * @param name The name of the particle system
  59490. * @param options The options used to create the system
  59491. * @param scene The scene the particle system belongs to
  59492. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59493. */
  59494. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  59495. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59496. /**
  59497. * The emitter represents the Mesh or position we are attaching the particle system to.
  59498. */
  59499. this.emitter = null;
  59500. /**
  59501. * The rendering group used by the Particle system to chose when to render.
  59502. */
  59503. this.renderingGroupId = 0;
  59504. /**
  59505. * The layer mask we are rendering the particles through.
  59506. */
  59507. this.layerMask = 0x0FFFFFFF;
  59508. this._accumulatedCount = 0;
  59509. this._targetIndex = 0;
  59510. this._currentRenderId = -1;
  59511. this._started = false;
  59512. this._stopped = false;
  59513. this._timeDelta = 0;
  59514. this._attributesStrideSize = 21;
  59515. this._actualFrame = 0;
  59516. this._rawTextureWidth = 256;
  59517. /**
  59518. * List of animations used by the particle system.
  59519. */
  59520. this.animations = [];
  59521. /**
  59522. * An event triggered when the system is disposed.
  59523. */
  59524. this.onDisposeObservable = new BABYLON.Observable();
  59525. /**
  59526. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59527. */
  59528. this.updateSpeed = 0.01;
  59529. /**
  59530. * The amount of time the particle system is running (depends of the overall update speed).
  59531. */
  59532. this.targetStopDuration = 0;
  59533. /**
  59534. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59535. */
  59536. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59537. /**
  59538. * Minimum life time of emitting particles.
  59539. */
  59540. this.minLifeTime = 1;
  59541. /**
  59542. * Maximum life time of emitting particles.
  59543. */
  59544. this.maxLifeTime = 1;
  59545. /**
  59546. * Minimum Size of emitting particles.
  59547. */
  59548. this.minSize = 1;
  59549. /**
  59550. * Maximum Size of emitting particles.
  59551. */
  59552. this.maxSize = 1;
  59553. /**
  59554. * Minimum scale of emitting particles on X axis.
  59555. */
  59556. this.minScaleX = 1;
  59557. /**
  59558. * Maximum scale of emitting particles on X axis.
  59559. */
  59560. this.maxScaleX = 1;
  59561. /**
  59562. * Minimum scale of emitting particles on Y axis.
  59563. */
  59564. this.minScaleY = 1;
  59565. /**
  59566. * Maximum scale of emitting particles on Y axis.
  59567. */
  59568. this.maxScaleY = 1;
  59569. /**
  59570. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59571. */
  59572. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59573. /**
  59574. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59575. */
  59576. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59577. /**
  59578. * Color the particle will have at the end of its lifetime.
  59579. */
  59580. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  59581. /**
  59582. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  59583. */
  59584. this.emitRate = 100;
  59585. /**
  59586. * You can use gravity if you want to give an orientation to your particles.
  59587. */
  59588. this.gravity = BABYLON.Vector3.Zero();
  59589. /**
  59590. * Minimum power of emitting particles.
  59591. */
  59592. this.minEmitPower = 1;
  59593. /**
  59594. * Maximum power of emitting particles.
  59595. */
  59596. this.maxEmitPower = 1;
  59597. /**
  59598. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59599. */
  59600. this.minAngularSpeed = 0;
  59601. /**
  59602. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59603. */
  59604. this.maxAngularSpeed = 0;
  59605. /**
  59606. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59607. * to override the particles.
  59608. */
  59609. this.forceDepthWrite = false;
  59610. this._preWarmDone = false;
  59611. /** 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 */
  59612. this.preWarmCycles = 0;
  59613. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59614. this.preWarmStepOffset = 1;
  59615. /**
  59616. * Gets or sets the minimal initial rotation in radians.
  59617. */
  59618. this.minInitialRotation = 0;
  59619. /**
  59620. * Gets or sets the maximal initial rotation in radians.
  59621. */
  59622. this.maxInitialRotation = 0;
  59623. /**
  59624. * 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)
  59625. */
  59626. this.spriteCellChangeSpeed = 1;
  59627. /**
  59628. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59629. */
  59630. this.startSpriteCellID = 0;
  59631. /**
  59632. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59633. */
  59634. this.endSpriteCellID = 0;
  59635. /**
  59636. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59637. */
  59638. this.spriteCellWidth = 0;
  59639. /**
  59640. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59641. */
  59642. this.spriteCellHeight = 0;
  59643. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59644. this.translationPivot = new BABYLON.Vector2(0, 0);
  59645. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59646. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59647. /**
  59648. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59649. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  59650. */
  59651. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59652. this._isBillboardBased = true;
  59653. this._colorGradients = null;
  59654. this._angularSpeedGradients = null;
  59655. this._sizeGradients = null;
  59656. this._velocityGradients = null;
  59657. this.id = name;
  59658. this.name = name;
  59659. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59660. this._engine = this._scene.getEngine();
  59661. if (!options.randomTextureSize) {
  59662. delete options.randomTextureSize;
  59663. }
  59664. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  59665. var optionsAsNumber = options;
  59666. if (isFinite(optionsAsNumber)) {
  59667. fullOptions.capacity = optionsAsNumber;
  59668. }
  59669. this._capacity = fullOptions.capacity;
  59670. this._activeCount = fullOptions.capacity;
  59671. this._currentActiveCount = 0;
  59672. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59673. this._scene.particleSystems.push(this);
  59674. this._updateEffectOptions = {
  59675. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  59676. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  59677. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  59678. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  59679. uniformBuffersNames: [],
  59680. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  59681. defines: "",
  59682. fallbacks: null,
  59683. onCompiled: null,
  59684. onError: null,
  59685. indexParameters: null,
  59686. maxSimultaneousLights: 0,
  59687. transformFeedbackVaryings: []
  59688. };
  59689. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59690. // Random data
  59691. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  59692. var d = [];
  59693. for (var i = 0; i < maxTextureSize; ++i) {
  59694. d.push(Math.random());
  59695. d.push(Math.random());
  59696. d.push(Math.random());
  59697. d.push(Math.random());
  59698. }
  59699. 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);
  59700. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59701. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59702. d = [];
  59703. for (var i = 0; i < maxTextureSize; ++i) {
  59704. d.push(Math.random());
  59705. d.push(Math.random());
  59706. d.push(Math.random());
  59707. d.push(Math.random());
  59708. }
  59709. 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);
  59710. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59711. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59712. this._randomTextureSize = maxTextureSize;
  59713. }
  59714. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  59715. /**
  59716. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  59717. */
  59718. get: function () {
  59719. if (!BABYLON.Engine.LastCreatedEngine) {
  59720. return false;
  59721. }
  59722. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  59723. },
  59724. enumerable: true,
  59725. configurable: true
  59726. });
  59727. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  59728. /**
  59729. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59730. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59731. */
  59732. get: function () {
  59733. if (this.particleEmitterType.direction1) {
  59734. return this.particleEmitterType.direction1;
  59735. }
  59736. return BABYLON.Vector3.Zero();
  59737. },
  59738. set: function (value) {
  59739. if (this.particleEmitterType.direction1) {
  59740. this.particleEmitterType.direction1 = value;
  59741. }
  59742. },
  59743. enumerable: true,
  59744. configurable: true
  59745. });
  59746. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  59747. /**
  59748. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59749. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59750. */
  59751. get: function () {
  59752. if (this.particleEmitterType.direction2) {
  59753. return this.particleEmitterType.direction2;
  59754. }
  59755. return BABYLON.Vector3.Zero();
  59756. },
  59757. set: function (value) {
  59758. if (this.particleEmitterType.direction2) {
  59759. this.particleEmitterType.direction2 = value;
  59760. }
  59761. },
  59762. enumerable: true,
  59763. configurable: true
  59764. });
  59765. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  59766. /**
  59767. * 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.
  59768. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59769. */
  59770. get: function () {
  59771. if (this.particleEmitterType.minEmitBox) {
  59772. return this.particleEmitterType.minEmitBox;
  59773. }
  59774. return BABYLON.Vector3.Zero();
  59775. },
  59776. set: function (value) {
  59777. if (this.particleEmitterType.minEmitBox) {
  59778. this.particleEmitterType.minEmitBox = value;
  59779. }
  59780. },
  59781. enumerable: true,
  59782. configurable: true
  59783. });
  59784. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  59785. /**
  59786. * 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.
  59787. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59788. */
  59789. get: function () {
  59790. if (this.particleEmitterType.maxEmitBox) {
  59791. return this.particleEmitterType.maxEmitBox;
  59792. }
  59793. return BABYLON.Vector3.Zero();
  59794. },
  59795. set: function (value) {
  59796. if (this.particleEmitterType.maxEmitBox) {
  59797. this.particleEmitterType.maxEmitBox = value;
  59798. }
  59799. },
  59800. enumerable: true,
  59801. configurable: true
  59802. });
  59803. /**
  59804. * Gets the maximum number of particles active at the same time.
  59805. * @returns The max number of active particles.
  59806. */
  59807. GPUParticleSystem.prototype.getCapacity = function () {
  59808. return this._capacity;
  59809. };
  59810. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  59811. /**
  59812. * Gets or set the number of active particles
  59813. */
  59814. get: function () {
  59815. return this._activeCount;
  59816. },
  59817. set: function (value) {
  59818. this._activeCount = Math.min(value, this._capacity);
  59819. },
  59820. enumerable: true,
  59821. configurable: true
  59822. });
  59823. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  59824. /**
  59825. * Gets whether an animation sprite sheet is enabled or not on the particle system
  59826. */
  59827. get: function () {
  59828. return this._isAnimationSheetEnabled;
  59829. },
  59830. enumerable: true,
  59831. configurable: true
  59832. });
  59833. /**
  59834. * Is this system ready to be used/rendered
  59835. * @return true if the system is ready
  59836. */
  59837. GPUParticleSystem.prototype.isReady = function () {
  59838. if (!this._updateEffect) {
  59839. this._recreateUpdateEffect();
  59840. this._recreateRenderEffect();
  59841. return false;
  59842. }
  59843. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59844. return false;
  59845. }
  59846. return true;
  59847. };
  59848. /**
  59849. * Gets Wether the system has been started.
  59850. * @returns True if it has been started, otherwise false.
  59851. */
  59852. GPUParticleSystem.prototype.isStarted = function () {
  59853. return this._started;
  59854. };
  59855. /**
  59856. * Starts the particle system and begins to emit
  59857. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  59858. */
  59859. GPUParticleSystem.prototype.start = function (delay) {
  59860. var _this = this;
  59861. if (delay === void 0) { delay = 0; }
  59862. if (delay) {
  59863. setTimeout(function () {
  59864. _this.start(0);
  59865. }, delay);
  59866. return;
  59867. }
  59868. this._started = true;
  59869. this._stopped = false;
  59870. this._preWarmDone = false;
  59871. };
  59872. /**
  59873. * Stops the particle system.
  59874. */
  59875. GPUParticleSystem.prototype.stop = function () {
  59876. this._stopped = true;
  59877. };
  59878. /**
  59879. * Remove all active particles
  59880. */
  59881. GPUParticleSystem.prototype.reset = function () {
  59882. this._releaseBuffers();
  59883. this._releaseVAOs();
  59884. this._currentActiveCount = 0;
  59885. this._targetIndex = 0;
  59886. };
  59887. /**
  59888. * Returns the string "GPUParticleSystem"
  59889. * @returns a string containing the class name
  59890. */
  59891. GPUParticleSystem.prototype.getClassName = function () {
  59892. return "GPUParticleSystem";
  59893. };
  59894. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  59895. /**
  59896. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  59897. */
  59898. get: function () {
  59899. return this._isBillboardBased;
  59900. },
  59901. set: function (value) {
  59902. if (this._isBillboardBased === value) {
  59903. return;
  59904. }
  59905. this._isBillboardBased = value;
  59906. this._releaseBuffers();
  59907. },
  59908. enumerable: true,
  59909. configurable: true
  59910. });
  59911. /**
  59912. * Gets the current list of color gradients.
  59913. * You must use addColorGradient and removeColorGradient to udpate this list
  59914. * @returns the list of color gradients
  59915. */
  59916. GPUParticleSystem.prototype.getColorGradients = function () {
  59917. return this._colorGradients;
  59918. };
  59919. /**
  59920. * Gets the current list of size gradients.
  59921. * You must use addSizeGradient and removeSizeGradient to udpate this list
  59922. * @returns the list of size gradients
  59923. */
  59924. GPUParticleSystem.prototype.getSizeGradients = function () {
  59925. return this._sizeGradients;
  59926. };
  59927. /**
  59928. * Gets the current list of angular speed gradients.
  59929. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  59930. * @returns the list of angular speed gradients
  59931. */
  59932. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  59933. return this._angularSpeedGradients;
  59934. };
  59935. /**
  59936. * Gets the current list of velocity gradients.
  59937. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  59938. * @returns the list of angular speed gradients
  59939. */
  59940. GPUParticleSystem.prototype.getVelocityGradients = function () {
  59941. return this._velocityGradients;
  59942. };
  59943. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  59944. if (!gradients) {
  59945. return this;
  59946. }
  59947. var index = 0;
  59948. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59949. var valueGradient = gradients_1[_i];
  59950. if (valueGradient.gradient === gradient) {
  59951. gradients.splice(index, 1);
  59952. break;
  59953. }
  59954. index++;
  59955. }
  59956. if (texture) {
  59957. texture.dispose();
  59958. }
  59959. this._releaseBuffers();
  59960. return this;
  59961. };
  59962. /**
  59963. * Adds a new color gradient
  59964. * @param gradient defines the gradient to use (between 0 and 1)
  59965. * @param color defines the color to affect to the specified gradient
  59966. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59967. * @returns the current particle system
  59968. */
  59969. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59970. if (!this._colorGradients) {
  59971. this._colorGradients = [];
  59972. }
  59973. var colorGradient = new BABYLON.ColorGradient();
  59974. colorGradient.gradient = gradient;
  59975. colorGradient.color1 = color1;
  59976. this._colorGradients.push(colorGradient);
  59977. this._colorGradients.sort(function (a, b) {
  59978. if (a.gradient < b.gradient) {
  59979. return -1;
  59980. }
  59981. else if (a.gradient > b.gradient) {
  59982. return 1;
  59983. }
  59984. return 0;
  59985. });
  59986. if (this._colorGradientsTexture) {
  59987. this._colorGradientsTexture.dispose();
  59988. this._colorGradientsTexture = null;
  59989. }
  59990. this._releaseBuffers();
  59991. return this;
  59992. };
  59993. /**
  59994. * Remove a specific color gradient
  59995. * @param gradient defines the gradient to remove
  59996. * @returns the current particle system
  59997. */
  59998. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  59999. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  60000. this._colorGradientsTexture = null;
  60001. return this;
  60002. };
  60003. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  60004. var valueGradient = new BABYLON.FactorGradient();
  60005. valueGradient.gradient = gradient;
  60006. valueGradient.factor1 = factor;
  60007. factorGradients.push(valueGradient);
  60008. factorGradients.sort(function (a, b) {
  60009. if (a.gradient < b.gradient) {
  60010. return -1;
  60011. }
  60012. else if (a.gradient > b.gradient) {
  60013. return 1;
  60014. }
  60015. return 0;
  60016. });
  60017. this._releaseBuffers();
  60018. };
  60019. /**
  60020. * Adds a new size gradient
  60021. * @param gradient defines the gradient to use (between 0 and 1)
  60022. * @param factor defines the size factor to affect to the specified gradient
  60023. * @returns the current particle system
  60024. */
  60025. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  60026. if (!this._sizeGradients) {
  60027. this._sizeGradients = [];
  60028. }
  60029. this._addFactorGradient(this._sizeGradients, gradient, factor);
  60030. if (this._sizeGradientsTexture) {
  60031. this._sizeGradientsTexture.dispose();
  60032. this._sizeGradientsTexture = null;
  60033. }
  60034. this._releaseBuffers();
  60035. return this;
  60036. };
  60037. /**
  60038. * Remove a specific size gradient
  60039. * @param gradient defines the gradient to remove
  60040. * @returns the current particle system
  60041. */
  60042. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60043. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  60044. this._sizeGradientsTexture = null;
  60045. return this;
  60046. };
  60047. /**
  60048. * Adds a new angular speed gradient
  60049. * @param gradient defines the gradient to use (between 0 and 1)
  60050. * @param factor defines the size factor to affect to the specified gradient
  60051. * @returns the current particle system
  60052. */
  60053. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  60054. if (!this._angularSpeedGradients) {
  60055. this._angularSpeedGradients = [];
  60056. }
  60057. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  60058. if (this._angularSpeedGradientsTexture) {
  60059. this._angularSpeedGradientsTexture.dispose();
  60060. this._angularSpeedGradientsTexture = null;
  60061. }
  60062. this._releaseBuffers();
  60063. return this;
  60064. };
  60065. /**
  60066. * Remove a specific angular speed gradient
  60067. * @param gradient defines the gradient to remove
  60068. * @returns the current particle system
  60069. */
  60070. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60071. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  60072. this._angularSpeedGradientsTexture = null;
  60073. return this;
  60074. };
  60075. /**
  60076. * Adds a new velocity gradient
  60077. * @param gradient defines the gradient to use (between 0 and 1)
  60078. * @param factor defines the size factor to affect to the specified gradient
  60079. * @returns the current particle system
  60080. */
  60081. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  60082. if (!this._velocityGradients) {
  60083. this._velocityGradients = [];
  60084. }
  60085. this._addFactorGradient(this._velocityGradients, gradient, factor);
  60086. if (this._velocityGradientsTexture) {
  60087. this._velocityGradientsTexture.dispose();
  60088. this._velocityGradientsTexture = null;
  60089. }
  60090. this._releaseBuffers();
  60091. return this;
  60092. };
  60093. /**
  60094. * Remove a specific velocity gradient
  60095. * @param gradient defines the gradient to remove
  60096. * @returns the current particle system
  60097. */
  60098. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60099. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  60100. this._velocityGradientsTexture = null;
  60101. return this;
  60102. };
  60103. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60104. var updateVertexBuffers = {};
  60105. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60106. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60107. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60108. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60109. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60110. var offset = 12;
  60111. if (!this._colorGradientsTexture) {
  60112. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60113. offset += 4;
  60114. }
  60115. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60116. offset += 3;
  60117. if (!this._isBillboardBased) {
  60118. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60119. offset += 3;
  60120. }
  60121. if (this._angularSpeedGradientsTexture) {
  60122. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60123. offset += 1;
  60124. }
  60125. else {
  60126. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60127. offset += 2;
  60128. }
  60129. if (this._isAnimationSheetEnabled) {
  60130. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60131. offset += 1;
  60132. }
  60133. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60134. this._engine.bindArrayBuffer(null);
  60135. return vao;
  60136. };
  60137. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60138. var renderVertexBuffers = {};
  60139. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  60140. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  60141. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  60142. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  60143. var offset = 12;
  60144. if (!this._colorGradientsTexture) {
  60145. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  60146. offset += 4;
  60147. }
  60148. offset += 3; // Direction
  60149. if (!this._isBillboardBased) {
  60150. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  60151. offset += 3;
  60152. }
  60153. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  60154. if (this._angularSpeedGradientsTexture) {
  60155. offset++;
  60156. }
  60157. else {
  60158. offset += 2;
  60159. }
  60160. if (this._isAnimationSheetEnabled) {
  60161. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  60162. offset += 1;
  60163. }
  60164. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  60165. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  60166. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  60167. this._engine.bindArrayBuffer(null);
  60168. return vao;
  60169. };
  60170. GPUParticleSystem.prototype._initialize = function (force) {
  60171. if (force === void 0) { force = false; }
  60172. if (this._buffer0 && !force) {
  60173. return;
  60174. }
  60175. var engine = this._scene.getEngine();
  60176. var data = new Array();
  60177. if (!this.isBillboardBased) {
  60178. this._attributesStrideSize += 3;
  60179. }
  60180. if (this._colorGradientsTexture) {
  60181. this._attributesStrideSize -= 4;
  60182. }
  60183. if (this._angularSpeedGradientsTexture) {
  60184. this._attributesStrideSize -= 1;
  60185. }
  60186. if (this._isAnimationSheetEnabled) {
  60187. this._attributesStrideSize += 1;
  60188. }
  60189. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  60190. // position
  60191. data.push(0.0);
  60192. data.push(0.0);
  60193. data.push(0.0);
  60194. // Age and life
  60195. data.push(0.0); // create the particle as a dead one to create a new one at start
  60196. data.push(0.0);
  60197. // Seed
  60198. data.push(Math.random());
  60199. data.push(Math.random());
  60200. data.push(Math.random());
  60201. data.push(Math.random());
  60202. // Size
  60203. data.push(0.0);
  60204. data.push(0.0);
  60205. data.push(0.0);
  60206. if (!this._colorGradientsTexture) {
  60207. // color
  60208. data.push(0.0);
  60209. data.push(0.0);
  60210. data.push(0.0);
  60211. data.push(0.0);
  60212. }
  60213. // direction
  60214. data.push(0.0);
  60215. data.push(0.0);
  60216. data.push(0.0);
  60217. if (!this.isBillboardBased) {
  60218. // initialDirection
  60219. data.push(0.0);
  60220. data.push(0.0);
  60221. data.push(0.0);
  60222. }
  60223. // angle
  60224. data.push(0.0);
  60225. if (!this._angularSpeedGradientsTexture) {
  60226. data.push(0.0);
  60227. }
  60228. if (this._isAnimationSheetEnabled) {
  60229. data.push(0.0);
  60230. }
  60231. }
  60232. // Sprite data
  60233. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  60234. -0.5, 0.5, 0, 1,
  60235. -0.5, -0.5, 0, 0,
  60236. 0.5, -0.5, 1, 0]);
  60237. // Buffers
  60238. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60239. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60240. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  60241. // Update VAO
  60242. this._updateVAO = [];
  60243. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  60244. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  60245. // Render VAO
  60246. this._renderVAO = [];
  60247. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  60248. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  60249. // Links
  60250. this._sourceBuffer = this._buffer0;
  60251. this._targetBuffer = this._buffer1;
  60252. };
  60253. /** @hidden */
  60254. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  60255. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  60256. if (this._isBillboardBased) {
  60257. defines += "\n#define BILLBOARD";
  60258. }
  60259. if (this._colorGradientsTexture) {
  60260. defines += "\n#define COLORGRADIENTS";
  60261. }
  60262. if (this._sizeGradientsTexture) {
  60263. defines += "\n#define SIZEGRADIENTS";
  60264. }
  60265. if (this._angularSpeedGradientsTexture) {
  60266. defines += "\n#define ANGULARSPEEDGRADIENTS";
  60267. }
  60268. if (this._velocityGradientsTexture) {
  60269. defines += "\n#define VELOCITYGRADIENTS";
  60270. }
  60271. if (this.isAnimationSheetEnabled) {
  60272. defines += "\n#define ANIMATESHEET";
  60273. }
  60274. if (this.noiseTexture) {
  60275. defines += "\n#define NOISE";
  60276. }
  60277. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  60278. return;
  60279. }
  60280. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  60281. if (!this._colorGradientsTexture) {
  60282. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  60283. }
  60284. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  60285. if (!this._isBillboardBased) {
  60286. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  60287. }
  60288. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  60289. if (this.isAnimationSheetEnabled) {
  60290. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  60291. }
  60292. this._updateEffectOptions.defines = defines;
  60293. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  60294. };
  60295. /** @hidden */
  60296. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  60297. var defines = "";
  60298. if (this._scene.clipPlane) {
  60299. defines = "\n#define CLIPPLANE";
  60300. }
  60301. if (this._isBillboardBased) {
  60302. defines += "\n#define BILLBOARD";
  60303. switch (this.billboardMode) {
  60304. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  60305. defines += "\n#define BILLBOARDY";
  60306. break;
  60307. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  60308. default:
  60309. break;
  60310. }
  60311. }
  60312. if (this._colorGradientsTexture) {
  60313. defines += "\n#define COLORGRADIENTS";
  60314. }
  60315. if (this.isAnimationSheetEnabled) {
  60316. defines += "\n#define ANIMATESHEET";
  60317. }
  60318. if (this._renderEffect && this._renderEffect.defines === defines) {
  60319. return;
  60320. }
  60321. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  60322. };
  60323. /**
  60324. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60325. * @param preWarm defines if we are in the pre-warmimg phase
  60326. */
  60327. GPUParticleSystem.prototype.animate = function (preWarm) {
  60328. if (preWarm === void 0) { preWarm = false; }
  60329. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60330. this._actualFrame += this._timeDelta;
  60331. if (!this._stopped) {
  60332. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60333. this.stop();
  60334. }
  60335. }
  60336. };
  60337. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  60338. var texture = this[textureName];
  60339. if (!factorGradients || !factorGradients.length || texture) {
  60340. return;
  60341. }
  60342. var data = new Float32Array(this._rawTextureWidth);
  60343. for (var x = 0; x < this._rawTextureWidth; x++) {
  60344. var ratio = x / this._rawTextureWidth;
  60345. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  60346. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60347. });
  60348. }
  60349. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60350. };
  60351. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  60352. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  60353. };
  60354. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  60355. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  60356. };
  60357. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  60358. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  60359. };
  60360. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  60361. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  60362. return;
  60363. }
  60364. var data = new Uint8Array(this._rawTextureWidth * 4);
  60365. var tmpColor = BABYLON.Tmp.Color4[0];
  60366. for (var x = 0; x < this._rawTextureWidth; x++) {
  60367. var ratio = x / this._rawTextureWidth;
  60368. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  60369. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  60370. data[x * 4] = tmpColor.r * 255;
  60371. data[x * 4 + 1] = tmpColor.g * 255;
  60372. data[x * 4 + 2] = tmpColor.b * 255;
  60373. data[x * 4 + 3] = tmpColor.a * 255;
  60374. });
  60375. }
  60376. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60377. };
  60378. /**
  60379. * Renders the particle system in its current state
  60380. * @param preWarm defines if the system should only update the particles but not render them
  60381. * @returns the current number of particles
  60382. */
  60383. GPUParticleSystem.prototype.render = function (preWarm) {
  60384. if (preWarm === void 0) { preWarm = false; }
  60385. if (!this._started) {
  60386. return 0;
  60387. }
  60388. this._createColorGradientTexture();
  60389. this._createSizeGradientTexture();
  60390. this._createAngularSpeedGradientTexture();
  60391. this._createVelocityGradientTexture();
  60392. this._recreateUpdateEffect();
  60393. this._recreateRenderEffect();
  60394. if (!this.isReady()) {
  60395. return 0;
  60396. }
  60397. if (!preWarm) {
  60398. if (!this._preWarmDone && this.preWarmCycles) {
  60399. for (var index = 0; index < this.preWarmCycles; index++) {
  60400. this.animate(true);
  60401. this.render(true);
  60402. }
  60403. this._preWarmDone = true;
  60404. }
  60405. if (this._currentRenderId === this._scene.getRenderId()) {
  60406. return 0;
  60407. }
  60408. this._currentRenderId = this._scene.getRenderId();
  60409. }
  60410. // Get everything ready to render
  60411. this._initialize();
  60412. this._accumulatedCount += this.emitRate * this._timeDelta;
  60413. if (this._accumulatedCount > 1) {
  60414. var intPart = this._accumulatedCount | 0;
  60415. this._accumulatedCount -= intPart;
  60416. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  60417. }
  60418. if (!this._currentActiveCount) {
  60419. return 0;
  60420. }
  60421. // Enable update effect
  60422. this._engine.enableEffect(this._updateEffect);
  60423. this._engine.setState(false);
  60424. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  60425. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  60426. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  60427. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  60428. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  60429. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  60430. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  60431. if (!this._colorGradientsTexture) {
  60432. this._updateEffect.setDirectColor4("color1", this.color1);
  60433. this._updateEffect.setDirectColor4("color2", this.color2);
  60434. }
  60435. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  60436. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  60437. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  60438. this._updateEffect.setVector3("gravity", this.gravity);
  60439. if (this._sizeGradientsTexture) {
  60440. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  60441. }
  60442. if (this._angularSpeedGradientsTexture) {
  60443. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  60444. }
  60445. if (this._velocityGradientsTexture) {
  60446. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  60447. }
  60448. if (this.particleEmitterType) {
  60449. this.particleEmitterType.applyToShader(this._updateEffect);
  60450. }
  60451. if (this._isAnimationSheetEnabled) {
  60452. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  60453. }
  60454. if (this.noiseTexture) {
  60455. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  60456. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  60457. }
  60458. var emitterWM;
  60459. if (this.emitter.position) {
  60460. var emitterMesh = this.emitter;
  60461. emitterWM = emitterMesh.getWorldMatrix();
  60462. }
  60463. else {
  60464. var emitterPosition = this.emitter;
  60465. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60466. }
  60467. this._updateEffect.setMatrix("emitterWM", emitterWM);
  60468. // Bind source VAO
  60469. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  60470. // Update
  60471. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  60472. this._engine.setRasterizerState(false);
  60473. this._engine.beginTransformFeedback(true);
  60474. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  60475. this._engine.endTransformFeedback();
  60476. this._engine.setRasterizerState(true);
  60477. this._engine.bindTransformFeedbackBuffer(null);
  60478. if (!preWarm) {
  60479. // Enable render effect
  60480. this._engine.enableEffect(this._renderEffect);
  60481. var viewMatrix = this._scene.getViewMatrix();
  60482. this._renderEffect.setMatrix("view", viewMatrix);
  60483. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  60484. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  60485. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  60486. if (this._colorGradientsTexture) {
  60487. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  60488. }
  60489. else {
  60490. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  60491. }
  60492. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60493. var baseSize = this.particleTexture.getBaseSize();
  60494. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60495. }
  60496. if (this._isBillboardBased) {
  60497. var camera = this._scene.activeCamera;
  60498. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  60499. }
  60500. if (this._scene.clipPlane) {
  60501. var clipPlane = this._scene.clipPlane;
  60502. var invView = viewMatrix.clone();
  60503. invView.invert();
  60504. this._renderEffect.setMatrix("invView", invView);
  60505. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  60506. }
  60507. // Draw order
  60508. switch (this.blendMode) {
  60509. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  60510. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60511. break;
  60512. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  60513. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60514. break;
  60515. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  60516. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60517. break;
  60518. }
  60519. if (this.forceDepthWrite) {
  60520. this._engine.setDepthWrite(true);
  60521. }
  60522. // Bind source VAO
  60523. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  60524. // Render
  60525. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  60526. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60527. }
  60528. // Switch VAOs
  60529. this._targetIndex++;
  60530. if (this._targetIndex === 2) {
  60531. this._targetIndex = 0;
  60532. }
  60533. // Switch buffers
  60534. var tmpBuffer = this._sourceBuffer;
  60535. this._sourceBuffer = this._targetBuffer;
  60536. this._targetBuffer = tmpBuffer;
  60537. return this._currentActiveCount;
  60538. };
  60539. /**
  60540. * Rebuilds the particle system
  60541. */
  60542. GPUParticleSystem.prototype.rebuild = function () {
  60543. this._initialize(true);
  60544. };
  60545. GPUParticleSystem.prototype._releaseBuffers = function () {
  60546. if (this._buffer0) {
  60547. this._buffer0.dispose();
  60548. this._buffer0 = null;
  60549. }
  60550. if (this._buffer1) {
  60551. this._buffer1.dispose();
  60552. this._buffer1 = null;
  60553. }
  60554. if (this._spriteBuffer) {
  60555. this._spriteBuffer.dispose();
  60556. this._spriteBuffer = null;
  60557. }
  60558. };
  60559. GPUParticleSystem.prototype._releaseVAOs = function () {
  60560. if (!this._updateVAO) {
  60561. return;
  60562. }
  60563. for (var index = 0; index < this._updateVAO.length; index++) {
  60564. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  60565. }
  60566. this._updateVAO = [];
  60567. for (var index = 0; index < this._renderVAO.length; index++) {
  60568. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  60569. }
  60570. this._renderVAO = [];
  60571. };
  60572. /**
  60573. * Disposes the particle system and free the associated resources
  60574. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60575. */
  60576. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  60577. if (disposeTexture === void 0) { disposeTexture = true; }
  60578. var index = this._scene.particleSystems.indexOf(this);
  60579. if (index > -1) {
  60580. this._scene.particleSystems.splice(index, 1);
  60581. }
  60582. this._releaseBuffers();
  60583. this._releaseVAOs();
  60584. if (this._colorGradientsTexture) {
  60585. this._colorGradientsTexture.dispose();
  60586. this._colorGradientsTexture = null;
  60587. }
  60588. if (this._sizeGradientsTexture) {
  60589. this._sizeGradientsTexture.dispose();
  60590. this._sizeGradientsTexture = null;
  60591. }
  60592. if (this._angularSpeedGradientsTexture) {
  60593. this._angularSpeedGradientsTexture.dispose();
  60594. this._angularSpeedGradientsTexture = null;
  60595. }
  60596. if (this._velocityGradientsTexture) {
  60597. this._velocityGradientsTexture.dispose();
  60598. this._velocityGradientsTexture = null;
  60599. }
  60600. if (this._randomTexture) {
  60601. this._randomTexture.dispose();
  60602. this._randomTexture = null;
  60603. }
  60604. if (this._randomTexture2) {
  60605. this._randomTexture2.dispose();
  60606. this._randomTexture2 = null;
  60607. }
  60608. if (disposeTexture && this.particleTexture) {
  60609. this.particleTexture.dispose();
  60610. this.particleTexture = null;
  60611. }
  60612. if (disposeTexture && this.noiseTexture) {
  60613. this.noiseTexture.dispose();
  60614. this.noiseTexture = null;
  60615. }
  60616. // Callback
  60617. this.onDisposeObservable.notifyObservers(this);
  60618. this.onDisposeObservable.clear();
  60619. };
  60620. /**
  60621. * Clones the particle system.
  60622. * @param name The name of the cloned object
  60623. * @param newEmitter The new emitter to use
  60624. * @returns the cloned particle system
  60625. */
  60626. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  60627. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  60628. BABYLON.Tools.DeepCopy(this, result);
  60629. if (newEmitter === undefined) {
  60630. newEmitter = this.emitter;
  60631. }
  60632. result.emitter = newEmitter;
  60633. if (this.particleTexture) {
  60634. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60635. }
  60636. return result;
  60637. };
  60638. /**
  60639. * Serializes the particle system to a JSON object.
  60640. * @returns the JSON object
  60641. */
  60642. GPUParticleSystem.prototype.serialize = function () {
  60643. var serializationObject = {};
  60644. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  60645. serializationObject.activeParticleCount = this.activeParticleCount;
  60646. return serializationObject;
  60647. };
  60648. /**
  60649. * Parses a JSON object to create a GPU particle system.
  60650. * @param parsedParticleSystem The JSON object to parse
  60651. * @param scene The scene to create the particle system in
  60652. * @param rootUrl The root url to use to load external dependencies like texture
  60653. * @returns the parsed GPU particle system
  60654. */
  60655. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  60656. var name = parsedParticleSystem.name;
  60657. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  60658. if (parsedParticleSystem.activeParticleCount) {
  60659. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  60660. }
  60661. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60662. return particleSystem;
  60663. };
  60664. return GPUParticleSystem;
  60665. }());
  60666. BABYLON.GPUParticleSystem = GPUParticleSystem;
  60667. })(BABYLON || (BABYLON = {}));
  60668. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  60669. var BABYLON;
  60670. (function (BABYLON) {
  60671. /**
  60672. * Represents one particle of a solid particle system.
  60673. */
  60674. var SolidParticle = /** @class */ (function () {
  60675. /**
  60676. * Creates a Solid Particle object.
  60677. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  60678. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  60679. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  60680. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  60681. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  60682. * @param shapeId (integer) is the model shape identifier in the SPS.
  60683. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  60684. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  60685. */
  60686. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  60687. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  60688. /**
  60689. * particle global index
  60690. */
  60691. this.idx = 0;
  60692. /**
  60693. * The color of the particle
  60694. */
  60695. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60696. /**
  60697. * The world space position of the particle.
  60698. */
  60699. this.position = BABYLON.Vector3.Zero();
  60700. /**
  60701. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  60702. */
  60703. this.rotation = BABYLON.Vector3.Zero();
  60704. /**
  60705. * The scaling of the particle.
  60706. */
  60707. this.scaling = BABYLON.Vector3.One();
  60708. /**
  60709. * The uvs of the particle.
  60710. */
  60711. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  60712. /**
  60713. * The current speed of the particle.
  60714. */
  60715. this.velocity = BABYLON.Vector3.Zero();
  60716. /**
  60717. * The pivot point in the particle local space.
  60718. */
  60719. this.pivot = BABYLON.Vector3.Zero();
  60720. /**
  60721. * Must the particle be translated from its pivot point in its local space ?
  60722. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  60723. * Default : false
  60724. */
  60725. this.translateFromPivot = false;
  60726. /**
  60727. * Is the particle active or not ?
  60728. */
  60729. this.alive = true;
  60730. /**
  60731. * Is the particle visible or not ?
  60732. */
  60733. this.isVisible = true;
  60734. /**
  60735. * Index of this particle in the global "positions" array (Internal use)
  60736. */
  60737. this._pos = 0;
  60738. /**
  60739. * Index of this particle in the global "indices" array (Internal use)
  60740. */
  60741. this._ind = 0;
  60742. /**
  60743. * ModelShape id of this particle
  60744. */
  60745. this.shapeId = 0;
  60746. /**
  60747. * Index of the particle in its shape id (Internal use)
  60748. */
  60749. this.idxInShape = 0;
  60750. /**
  60751. * Still set as invisible in order to skip useless computations (Internal use)
  60752. */
  60753. this._stillInvisible = false;
  60754. /**
  60755. * Last computed particle rotation matrix
  60756. */
  60757. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  60758. /**
  60759. * Parent particle Id, if any.
  60760. * Default null.
  60761. */
  60762. this.parentId = null;
  60763. /**
  60764. * Internal global position in the SPS.
  60765. */
  60766. this._globalPosition = BABYLON.Vector3.Zero();
  60767. this.idx = particleIndex;
  60768. this._pos = positionIndex;
  60769. this._ind = indiceIndex;
  60770. this._model = model;
  60771. this.shapeId = shapeId;
  60772. this.idxInShape = idxInShape;
  60773. this._sps = sps;
  60774. if (modelBoundingInfo) {
  60775. this._modelBoundingInfo = modelBoundingInfo;
  60776. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  60777. }
  60778. }
  60779. Object.defineProperty(SolidParticle.prototype, "scale", {
  60780. /**
  60781. * Legacy support, changed scale to scaling
  60782. */
  60783. get: function () {
  60784. return this.scaling;
  60785. },
  60786. /**
  60787. * Legacy support, changed scale to scaling
  60788. */
  60789. set: function (scale) {
  60790. this.scaling = scale;
  60791. },
  60792. enumerable: true,
  60793. configurable: true
  60794. });
  60795. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  60796. /**
  60797. * Legacy support, changed quaternion to rotationQuaternion
  60798. */
  60799. get: function () {
  60800. return this.rotationQuaternion;
  60801. },
  60802. /**
  60803. * Legacy support, changed quaternion to rotationQuaternion
  60804. */
  60805. set: function (q) {
  60806. this.rotationQuaternion = q;
  60807. },
  60808. enumerable: true,
  60809. configurable: true
  60810. });
  60811. /**
  60812. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  60813. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  60814. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  60815. * @returns true if it intersects
  60816. */
  60817. SolidParticle.prototype.intersectsMesh = function (target) {
  60818. if (!this._boundingInfo || !target._boundingInfo) {
  60819. return false;
  60820. }
  60821. if (this._sps._bSphereOnly) {
  60822. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  60823. }
  60824. return this._boundingInfo.intersects(target._boundingInfo, false);
  60825. };
  60826. return SolidParticle;
  60827. }());
  60828. BABYLON.SolidParticle = SolidParticle;
  60829. /**
  60830. * Represents the shape of the model used by one particle of a solid particle system.
  60831. * SPS internal tool, don't use it manually.
  60832. */
  60833. var ModelShape = /** @class */ (function () {
  60834. /**
  60835. * 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.
  60836. * SPS internal tool, don't use it manually.
  60837. * @hidden
  60838. */
  60839. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  60840. /**
  60841. * length of the shape in the model indices array (internal use)
  60842. */
  60843. this._indicesLength = 0;
  60844. this.shapeID = id;
  60845. this._shape = shape;
  60846. this._indicesLength = indicesLength;
  60847. this._shapeUV = shapeUV;
  60848. this._positionFunction = posFunction;
  60849. this._vertexFunction = vtxFunction;
  60850. }
  60851. return ModelShape;
  60852. }());
  60853. BABYLON.ModelShape = ModelShape;
  60854. /**
  60855. * Represents a Depth Sorted Particle in the solid particle system.
  60856. */
  60857. var DepthSortedParticle = /** @class */ (function () {
  60858. function DepthSortedParticle() {
  60859. /**
  60860. * Index of the particle in the "indices" array
  60861. */
  60862. this.ind = 0;
  60863. /**
  60864. * Length of the particle shape in the "indices" array
  60865. */
  60866. this.indicesLength = 0;
  60867. /**
  60868. * Squared distance from the particle to the camera
  60869. */
  60870. this.sqDistance = 0.0;
  60871. }
  60872. return DepthSortedParticle;
  60873. }());
  60874. BABYLON.DepthSortedParticle = DepthSortedParticle;
  60875. })(BABYLON || (BABYLON = {}));
  60876. //# sourceMappingURL=babylon.solidParticle.js.map
  60877. var BABYLON;
  60878. (function (BABYLON) {
  60879. /**
  60880. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  60881. *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.
  60882. * The SPS is also a particle system. It provides some methods to manage the particles.
  60883. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  60884. *
  60885. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  60886. */
  60887. var SolidParticleSystem = /** @class */ (function () {
  60888. /**
  60889. * Creates a SPS (Solid Particle System) object.
  60890. * @param name (String) is the SPS name, this will be the underlying mesh name.
  60891. * @param scene (Scene) is the scene in which the SPS is added.
  60892. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  60893. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  60894. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  60895. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  60896. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  60897. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  60898. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  60899. */
  60900. function SolidParticleSystem(name, scene, options) {
  60901. /**
  60902. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  60903. * Example : var p = SPS.particles[i];
  60904. */
  60905. this.particles = new Array();
  60906. /**
  60907. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  60908. */
  60909. this.nbParticles = 0;
  60910. /**
  60911. * If the particles must ever face the camera (default false). Useful for planar particles.
  60912. */
  60913. this.billboard = false;
  60914. /**
  60915. * Recompute normals when adding a shape
  60916. */
  60917. this.recomputeNormals = true;
  60918. /**
  60919. * This a counter ofr your own usage. It's not set by any SPS functions.
  60920. */
  60921. this.counter = 0;
  60922. /**
  60923. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  60924. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  60925. */
  60926. this.vars = {};
  60927. /**
  60928. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  60929. */
  60930. this._bSphereOnly = false;
  60931. /**
  60932. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  60933. */
  60934. this._bSphereRadiusFactor = 1.0;
  60935. this._positions = new Array();
  60936. this._indices = new Array();
  60937. this._normals = new Array();
  60938. this._colors = new Array();
  60939. this._uvs = new Array();
  60940. this._index = 0; // indices index
  60941. this._updatable = true;
  60942. this._pickable = false;
  60943. this._isVisibilityBoxLocked = false;
  60944. this._alwaysVisible = false;
  60945. this._depthSort = false;
  60946. this._shapeCounter = 0;
  60947. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  60948. this._color = new BABYLON.Color4(0, 0, 0, 0);
  60949. this._computeParticleColor = true;
  60950. this._computeParticleTexture = true;
  60951. this._computeParticleRotation = true;
  60952. this._computeParticleVertex = false;
  60953. this._computeBoundingBox = false;
  60954. this._depthSortParticles = true;
  60955. this._cam_axisZ = BABYLON.Vector3.Zero();
  60956. this._cam_axisY = BABYLON.Vector3.Zero();
  60957. this._cam_axisX = BABYLON.Vector3.Zero();
  60958. this._axisZ = BABYLON.Axis.Z;
  60959. this._camDir = BABYLON.Vector3.Zero();
  60960. this._camInvertedPosition = BABYLON.Vector3.Zero();
  60961. this._rotMatrix = new BABYLON.Matrix();
  60962. this._invertMatrix = new BABYLON.Matrix();
  60963. this._rotated = BABYLON.Vector3.Zero();
  60964. this._quaternion = new BABYLON.Quaternion();
  60965. this._vertex = BABYLON.Vector3.Zero();
  60966. this._normal = BABYLON.Vector3.Zero();
  60967. this._yaw = 0.0;
  60968. this._pitch = 0.0;
  60969. this._roll = 0.0;
  60970. this._halfroll = 0.0;
  60971. this._halfpitch = 0.0;
  60972. this._halfyaw = 0.0;
  60973. this._sinRoll = 0.0;
  60974. this._cosRoll = 0.0;
  60975. this._sinPitch = 0.0;
  60976. this._cosPitch = 0.0;
  60977. this._sinYaw = 0.0;
  60978. this._cosYaw = 0.0;
  60979. this._mustUnrotateFixedNormals = false;
  60980. this._minimum = BABYLON.Vector3.Zero();
  60981. this._maximum = BABYLON.Vector3.Zero();
  60982. this._minBbox = BABYLON.Vector3.Zero();
  60983. this._maxBbox = BABYLON.Vector3.Zero();
  60984. this._particlesIntersect = false;
  60985. this._depthSortFunction = function (p1, p2) {
  60986. return (p2.sqDistance - p1.sqDistance);
  60987. };
  60988. this._needs32Bits = false;
  60989. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  60990. this._scaledPivot = BABYLON.Vector3.Zero();
  60991. this._particleHasParent = false;
  60992. this.name = name;
  60993. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60994. this._camera = scene.activeCamera;
  60995. this._pickable = options ? options.isPickable : false;
  60996. this._depthSort = options ? options.enableDepthSort : false;
  60997. this._particlesIntersect = options ? options.particleIntersection : false;
  60998. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  60999. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  61000. if (options && options.updatable !== undefined) {
  61001. this._updatable = options.updatable;
  61002. }
  61003. else {
  61004. this._updatable = true;
  61005. }
  61006. if (this._pickable) {
  61007. this.pickedParticles = [];
  61008. }
  61009. if (this._depthSort) {
  61010. this.depthSortedParticles = [];
  61011. }
  61012. }
  61013. /**
  61014. * Builds the SPS underlying mesh. Returns a standard Mesh.
  61015. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  61016. * @returns the created mesh
  61017. */
  61018. SolidParticleSystem.prototype.buildMesh = function () {
  61019. if (this.nbParticles === 0) {
  61020. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  61021. this.addShape(triangle, 1);
  61022. triangle.dispose();
  61023. }
  61024. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  61025. this._positions32 = new Float32Array(this._positions);
  61026. this._uvs32 = new Float32Array(this._uvs);
  61027. this._colors32 = new Float32Array(this._colors);
  61028. if (this.recomputeNormals) {
  61029. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  61030. }
  61031. this._normals32 = new Float32Array(this._normals);
  61032. this._fixedNormal32 = new Float32Array(this._normals);
  61033. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  61034. this._unrotateFixedNormals();
  61035. }
  61036. var vertexData = new BABYLON.VertexData();
  61037. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  61038. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  61039. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  61040. if (this._uvs32.length > 0) {
  61041. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  61042. }
  61043. if (this._colors32.length > 0) {
  61044. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  61045. }
  61046. var mesh = new BABYLON.Mesh(this.name, this._scene);
  61047. vertexData.applyToMesh(mesh, this._updatable);
  61048. this.mesh = mesh;
  61049. this.mesh.isPickable = this._pickable;
  61050. // free memory
  61051. if (!this._depthSort) {
  61052. this._indices = null;
  61053. }
  61054. this._positions = null;
  61055. this._normals = null;
  61056. this._uvs = null;
  61057. this._colors = null;
  61058. if (!this._updatable) {
  61059. this.particles.length = 0;
  61060. }
  61061. return mesh;
  61062. };
  61063. /**
  61064. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  61065. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  61066. * Thus the particles generated from `digest()` have their property `position` set yet.
  61067. * @param mesh ( Mesh ) is the mesh to be digested
  61068. * @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
  61069. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  61070. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  61071. * @returns the current SPS
  61072. */
  61073. SolidParticleSystem.prototype.digest = function (mesh, options) {
  61074. var size = (options && options.facetNb) || 1;
  61075. var number = (options && options.number) || 0;
  61076. var delta = (options && options.delta) || 0;
  61077. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61078. var meshInd = mesh.getIndices();
  61079. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61080. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61081. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61082. var f = 0; // facet counter
  61083. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  61084. // compute size from number
  61085. if (number) {
  61086. number = (number > totalFacets) ? totalFacets : number;
  61087. size = Math.round(totalFacets / number);
  61088. delta = 0;
  61089. }
  61090. else {
  61091. size = (size > totalFacets) ? totalFacets : size;
  61092. }
  61093. var facetPos = []; // submesh positions
  61094. var facetInd = []; // submesh indices
  61095. var facetUV = []; // submesh UV
  61096. var facetCol = []; // submesh colors
  61097. var barycenter = BABYLON.Vector3.Zero();
  61098. var sizeO = size;
  61099. while (f < totalFacets) {
  61100. size = sizeO + Math.floor((1 + delta) * Math.random());
  61101. if (f > totalFacets - size) {
  61102. size = totalFacets - f;
  61103. }
  61104. // reset temp arrays
  61105. facetPos.length = 0;
  61106. facetInd.length = 0;
  61107. facetUV.length = 0;
  61108. facetCol.length = 0;
  61109. // iterate over "size" facets
  61110. var fi = 0;
  61111. for (var j = f * 3; j < (f + size) * 3; j++) {
  61112. facetInd.push(fi);
  61113. var i = meshInd[j];
  61114. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  61115. if (meshUV) {
  61116. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  61117. }
  61118. if (meshCol) {
  61119. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  61120. }
  61121. fi++;
  61122. }
  61123. // create a model shape for each single particle
  61124. var idx = this.nbParticles;
  61125. var shape = this._posToShape(facetPos);
  61126. var shapeUV = this._uvsToShapeUV(facetUV);
  61127. // compute the barycenter of the shape
  61128. var v;
  61129. for (v = 0; v < shape.length; v++) {
  61130. barycenter.addInPlace(shape[v]);
  61131. }
  61132. barycenter.scaleInPlace(1 / shape.length);
  61133. // shift the shape from its barycenter to the origin
  61134. for (v = 0; v < shape.length; v++) {
  61135. shape[v].subtractInPlace(barycenter);
  61136. }
  61137. var bInfo;
  61138. if (this._particlesIntersect) {
  61139. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  61140. }
  61141. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  61142. // add the particle in the SPS
  61143. var currentPos = this._positions.length;
  61144. var currentInd = this._indices.length;
  61145. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  61146. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  61147. // initialize the particle position
  61148. this.particles[this.nbParticles].position.addInPlace(barycenter);
  61149. this._index += shape.length;
  61150. idx++;
  61151. this.nbParticles++;
  61152. this._shapeCounter++;
  61153. f += size;
  61154. }
  61155. return this;
  61156. };
  61157. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  61158. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  61159. var index = 0;
  61160. var idx = 0;
  61161. for (var p = 0; p < this.particles.length; p++) {
  61162. this._particle = this.particles[p];
  61163. this._shape = this._particle._model._shape;
  61164. if (this._particle.rotationQuaternion) {
  61165. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61166. }
  61167. else {
  61168. this._yaw = this._particle.rotation.y;
  61169. this._pitch = this._particle.rotation.x;
  61170. this._roll = this._particle.rotation.z;
  61171. this._quaternionRotationYPR();
  61172. }
  61173. this._quaternionToRotationMatrix();
  61174. this._rotMatrix.invertToRef(this._invertMatrix);
  61175. for (var pt = 0; pt < this._shape.length; pt++) {
  61176. idx = index + pt * 3;
  61177. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  61178. this._fixedNormal32[idx] = this._normal.x;
  61179. this._fixedNormal32[idx + 1] = this._normal.y;
  61180. this._fixedNormal32[idx + 2] = this._normal.z;
  61181. }
  61182. index = idx + 3;
  61183. }
  61184. };
  61185. //reset copy
  61186. SolidParticleSystem.prototype._resetCopy = function () {
  61187. this._copy.position.x = 0;
  61188. this._copy.position.y = 0;
  61189. this._copy.position.z = 0;
  61190. this._copy.rotation.x = 0;
  61191. this._copy.rotation.y = 0;
  61192. this._copy.rotation.z = 0;
  61193. this._copy.rotationQuaternion = null;
  61194. this._copy.scaling.x = 1.0;
  61195. this._copy.scaling.y = 1.0;
  61196. this._copy.scaling.z = 1.0;
  61197. this._copy.uvs.x = 0;
  61198. this._copy.uvs.y = 0;
  61199. this._copy.uvs.z = 1.0;
  61200. this._copy.uvs.w = 1.0;
  61201. this._copy.color = null;
  61202. this._copy.translateFromPivot = false;
  61203. };
  61204. // _meshBuilder : inserts the shape model in the global SPS mesh
  61205. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  61206. var i;
  61207. var u = 0;
  61208. var c = 0;
  61209. var n = 0;
  61210. this._resetCopy();
  61211. if (options && options.positionFunction) { // call to custom positionFunction
  61212. options.positionFunction(this._copy, idx, idxInShape);
  61213. this._mustUnrotateFixedNormals = true;
  61214. }
  61215. if (this._copy.rotationQuaternion) {
  61216. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61217. }
  61218. else {
  61219. this._yaw = this._copy.rotation.y;
  61220. this._pitch = this._copy.rotation.x;
  61221. this._roll = this._copy.rotation.z;
  61222. this._quaternionRotationYPR();
  61223. }
  61224. this._quaternionToRotationMatrix();
  61225. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  61226. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  61227. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  61228. if (this._copy.translateFromPivot) {
  61229. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61230. }
  61231. else {
  61232. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61233. }
  61234. for (i = 0; i < shape.length; i++) {
  61235. this._vertex.x = shape[i].x;
  61236. this._vertex.y = shape[i].y;
  61237. this._vertex.z = shape[i].z;
  61238. if (options && options.vertexFunction) {
  61239. options.vertexFunction(this._copy, this._vertex, i);
  61240. }
  61241. this._vertex.x *= this._copy.scaling.x;
  61242. this._vertex.y *= this._copy.scaling.y;
  61243. this._vertex.z *= this._copy.scaling.z;
  61244. this._vertex.x -= this._scaledPivot.x;
  61245. this._vertex.y -= this._scaledPivot.y;
  61246. this._vertex.z -= this._scaledPivot.z;
  61247. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61248. this._rotated.addInPlace(this._pivotBackTranslation);
  61249. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  61250. if (meshUV) {
  61251. 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);
  61252. u += 2;
  61253. }
  61254. if (this._copy.color) {
  61255. this._color = this._copy.color;
  61256. }
  61257. else if (meshCol && meshCol[c] !== undefined) {
  61258. this._color.r = meshCol[c];
  61259. this._color.g = meshCol[c + 1];
  61260. this._color.b = meshCol[c + 2];
  61261. this._color.a = meshCol[c + 3];
  61262. }
  61263. else {
  61264. this._color.r = 1.0;
  61265. this._color.g = 1.0;
  61266. this._color.b = 1.0;
  61267. this._color.a = 1.0;
  61268. }
  61269. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  61270. c += 4;
  61271. if (!this.recomputeNormals && meshNor) {
  61272. this._normal.x = meshNor[n];
  61273. this._normal.y = meshNor[n + 1];
  61274. this._normal.z = meshNor[n + 2];
  61275. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  61276. normals.push(this._normal.x, this._normal.y, this._normal.z);
  61277. n += 3;
  61278. }
  61279. }
  61280. for (i = 0; i < meshInd.length; i++) {
  61281. var current_ind = p + meshInd[i];
  61282. indices.push(current_ind);
  61283. if (current_ind > 65535) {
  61284. this._needs32Bits = true;
  61285. }
  61286. }
  61287. if (this._pickable) {
  61288. var nbfaces = meshInd.length / 3;
  61289. for (i = 0; i < nbfaces; i++) {
  61290. this.pickedParticles.push({ idx: idx, faceId: i });
  61291. }
  61292. }
  61293. if (this._depthSort) {
  61294. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  61295. }
  61296. return this._copy;
  61297. };
  61298. // returns a shape array from positions array
  61299. SolidParticleSystem.prototype._posToShape = function (positions) {
  61300. var shape = [];
  61301. for (var i = 0; i < positions.length; i += 3) {
  61302. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  61303. }
  61304. return shape;
  61305. };
  61306. // returns a shapeUV array from a Vector4 uvs
  61307. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  61308. var shapeUV = [];
  61309. if (uvs) {
  61310. for (var i = 0; i < uvs.length; i++)
  61311. shapeUV.push(uvs[i]);
  61312. }
  61313. return shapeUV;
  61314. };
  61315. // adds a new particle object in the particles array
  61316. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  61317. if (bInfo === void 0) { bInfo = null; }
  61318. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  61319. this.particles.push(sp);
  61320. return sp;
  61321. };
  61322. /**
  61323. * Adds some particles to the SPS from the model shape. Returns the shape id.
  61324. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  61325. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  61326. * @param nb (positive integer) the number of particles to be created from this model
  61327. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  61328. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  61329. * @returns the number of shapes in the system
  61330. */
  61331. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  61332. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61333. var meshInd = mesh.getIndices();
  61334. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61335. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61336. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61337. var bbInfo;
  61338. if (this._particlesIntersect) {
  61339. bbInfo = mesh.getBoundingInfo();
  61340. }
  61341. var shape = this._posToShape(meshPos);
  61342. var shapeUV = this._uvsToShapeUV(meshUV);
  61343. var posfunc = options ? options.positionFunction : null;
  61344. var vtxfunc = options ? options.vertexFunction : null;
  61345. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  61346. // particles
  61347. var sp;
  61348. var currentCopy;
  61349. var idx = this.nbParticles;
  61350. for (var i = 0; i < nb; i++) {
  61351. var currentPos = this._positions.length;
  61352. var currentInd = this._indices.length;
  61353. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  61354. if (this._updatable) {
  61355. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  61356. sp.position.copyFrom(currentCopy.position);
  61357. sp.rotation.copyFrom(currentCopy.rotation);
  61358. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  61359. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  61360. }
  61361. if (currentCopy.color && sp.color) {
  61362. sp.color.copyFrom(currentCopy.color);
  61363. }
  61364. sp.scaling.copyFrom(currentCopy.scaling);
  61365. sp.uvs.copyFrom(currentCopy.uvs);
  61366. }
  61367. this._index += shape.length;
  61368. idx++;
  61369. }
  61370. this.nbParticles += nb;
  61371. this._shapeCounter++;
  61372. return this._shapeCounter - 1;
  61373. };
  61374. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  61375. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  61376. this._resetCopy();
  61377. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  61378. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  61379. }
  61380. if (this._copy.rotationQuaternion) {
  61381. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61382. }
  61383. else {
  61384. this._yaw = this._copy.rotation.y;
  61385. this._pitch = this._copy.rotation.x;
  61386. this._roll = this._copy.rotation.z;
  61387. this._quaternionRotationYPR();
  61388. }
  61389. this._quaternionToRotationMatrix();
  61390. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61391. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61392. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61393. if (this._copy.translateFromPivot) {
  61394. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61395. }
  61396. else {
  61397. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61398. }
  61399. this._shape = particle._model._shape;
  61400. for (var pt = 0; pt < this._shape.length; pt++) {
  61401. this._vertex.x = this._shape[pt].x;
  61402. this._vertex.y = this._shape[pt].y;
  61403. this._vertex.z = this._shape[pt].z;
  61404. if (particle._model._vertexFunction) {
  61405. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  61406. }
  61407. this._vertex.x *= this._copy.scaling.x;
  61408. this._vertex.y *= this._copy.scaling.y;
  61409. this._vertex.z *= this._copy.scaling.z;
  61410. this._vertex.x -= this._scaledPivot.x;
  61411. this._vertex.y -= this._scaledPivot.y;
  61412. this._vertex.z -= this._scaledPivot.z;
  61413. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61414. this._rotated.addInPlace(this._pivotBackTranslation);
  61415. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  61416. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  61417. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  61418. }
  61419. particle.position.x = 0.0;
  61420. particle.position.y = 0.0;
  61421. particle.position.z = 0.0;
  61422. particle.rotation.x = 0.0;
  61423. particle.rotation.y = 0.0;
  61424. particle.rotation.z = 0.0;
  61425. particle.rotationQuaternion = null;
  61426. particle.scaling.x = 1.0;
  61427. particle.scaling.y = 1.0;
  61428. particle.scaling.z = 1.0;
  61429. particle.uvs.x = 0.0;
  61430. particle.uvs.y = 0.0;
  61431. particle.uvs.z = 1.0;
  61432. particle.uvs.w = 1.0;
  61433. particle.pivot.x = 0.0;
  61434. particle.pivot.y = 0.0;
  61435. particle.pivot.z = 0.0;
  61436. particle.translateFromPivot = false;
  61437. particle.parentId = null;
  61438. };
  61439. /**
  61440. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  61441. * @returns the SPS.
  61442. */
  61443. SolidParticleSystem.prototype.rebuildMesh = function () {
  61444. for (var p = 0; p < this.particles.length; p++) {
  61445. this._rebuildParticle(this.particles[p]);
  61446. }
  61447. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61448. return this;
  61449. };
  61450. /**
  61451. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  61452. * This method calls `updateParticle()` for each particle of the SPS.
  61453. * For an animated SPS, it is usually called within the render loop.
  61454. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  61455. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  61456. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  61457. * @returns the SPS.
  61458. */
  61459. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  61460. if (start === void 0) { start = 0; }
  61461. if (end === void 0) { end = this.nbParticles - 1; }
  61462. if (update === void 0) { update = true; }
  61463. if (!this._updatable) {
  61464. return this;
  61465. }
  61466. // custom beforeUpdate
  61467. this.beforeUpdateParticles(start, end, update);
  61468. this._cam_axisX.x = 1.0;
  61469. this._cam_axisX.y = 0.0;
  61470. this._cam_axisX.z = 0.0;
  61471. this._cam_axisY.x = 0.0;
  61472. this._cam_axisY.y = 1.0;
  61473. this._cam_axisY.z = 0.0;
  61474. this._cam_axisZ.x = 0.0;
  61475. this._cam_axisZ.y = 0.0;
  61476. this._cam_axisZ.z = 1.0;
  61477. // cases when the World Matrix is to be computed first
  61478. if (this.billboard || this._depthSort) {
  61479. this.mesh.computeWorldMatrix(true);
  61480. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  61481. }
  61482. // if the particles will always face the camera
  61483. if (this.billboard) {
  61484. // compute the camera position and un-rotate it by the current mesh rotation
  61485. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  61486. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  61487. this._cam_axisZ.normalize();
  61488. // same for camera up vector extracted from the cam view matrix
  61489. var view = this._camera.getViewMatrix(true);
  61490. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  61491. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  61492. this._cam_axisY.normalize();
  61493. this._cam_axisX.normalize();
  61494. }
  61495. // if depthSort, compute the camera global position in the mesh local system
  61496. if (this._depthSort) {
  61497. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  61498. }
  61499. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  61500. var idx = 0; // current position index in the global array positions32
  61501. var index = 0; // position start index in the global array positions32 of the current particle
  61502. var colidx = 0; // current color index in the global array colors32
  61503. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  61504. var uvidx = 0; // current uv index in the global array uvs32
  61505. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  61506. var pt = 0; // current index in the particle model shape
  61507. if (this.mesh.isFacetDataEnabled) {
  61508. this._computeBoundingBox = true;
  61509. }
  61510. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  61511. if (this._computeBoundingBox) {
  61512. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  61513. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  61514. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  61515. }
  61516. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  61517. if (this.mesh._boundingInfo) {
  61518. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  61519. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  61520. }
  61521. }
  61522. }
  61523. // particle loop
  61524. index = this.particles[start]._pos;
  61525. var vpos = (index / 3) | 0;
  61526. colorIndex = vpos * 4;
  61527. uvIndex = vpos * 2;
  61528. for (var p = start; p <= end; p++) {
  61529. this._particle = this.particles[p];
  61530. this._shape = this._particle._model._shape;
  61531. this._shapeUV = this._particle._model._shapeUV;
  61532. // call to custom user function to update the particle properties
  61533. this.updateParticle(this._particle);
  61534. // camera-particle distance for depth sorting
  61535. if (this._depthSort && this._depthSortParticles) {
  61536. var dsp = this.depthSortedParticles[p];
  61537. dsp.ind = this._particle._ind;
  61538. dsp.indicesLength = this._particle._model._indicesLength;
  61539. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  61540. }
  61541. // skip the computations for inactive or already invisible particles
  61542. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  61543. // increment indexes for the next particle
  61544. pt = this._shape.length;
  61545. index += pt * 3;
  61546. colorIndex += pt * 4;
  61547. uvIndex += pt * 2;
  61548. continue;
  61549. }
  61550. if (this._particle.isVisible) {
  61551. this._particle._stillInvisible = false; // un-mark permanent invisibility
  61552. this._particleHasParent = (this._particle.parentId !== null);
  61553. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61554. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61555. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61556. // particle rotation matrix
  61557. if (this.billboard) {
  61558. this._particle.rotation.x = 0.0;
  61559. this._particle.rotation.y = 0.0;
  61560. }
  61561. if (this._computeParticleRotation || this.billboard) {
  61562. if (this._particle.rotationQuaternion) {
  61563. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61564. }
  61565. else {
  61566. this._yaw = this._particle.rotation.y;
  61567. this._pitch = this._particle.rotation.x;
  61568. this._roll = this._particle.rotation.z;
  61569. this._quaternionRotationYPR();
  61570. }
  61571. this._quaternionToRotationMatrix();
  61572. }
  61573. if (this._particleHasParent) {
  61574. this._parent = this.particles[this._particle.parentId];
  61575. 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];
  61576. 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];
  61577. 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];
  61578. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  61579. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  61580. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  61581. if (this._computeParticleRotation || this.billboard) {
  61582. 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];
  61583. 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];
  61584. 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];
  61585. 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];
  61586. 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];
  61587. 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];
  61588. 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];
  61589. 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];
  61590. 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];
  61591. }
  61592. }
  61593. else {
  61594. this._particle._globalPosition.x = this._particle.position.x;
  61595. this._particle._globalPosition.y = this._particle.position.y;
  61596. this._particle._globalPosition.z = this._particle.position.z;
  61597. if (this._computeParticleRotation || this.billboard) {
  61598. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  61599. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  61600. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  61601. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  61602. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  61603. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  61604. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  61605. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  61606. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  61607. }
  61608. }
  61609. if (this._particle.translateFromPivot) {
  61610. this._pivotBackTranslation.x = 0.0;
  61611. this._pivotBackTranslation.y = 0.0;
  61612. this._pivotBackTranslation.z = 0.0;
  61613. }
  61614. else {
  61615. this._pivotBackTranslation.x = this._scaledPivot.x;
  61616. this._pivotBackTranslation.y = this._scaledPivot.y;
  61617. this._pivotBackTranslation.z = this._scaledPivot.z;
  61618. }
  61619. // particle vertex loop
  61620. for (pt = 0; pt < this._shape.length; pt++) {
  61621. idx = index + pt * 3;
  61622. colidx = colorIndex + pt * 4;
  61623. uvidx = uvIndex + pt * 2;
  61624. this._vertex.x = this._shape[pt].x;
  61625. this._vertex.y = this._shape[pt].y;
  61626. this._vertex.z = this._shape[pt].z;
  61627. if (this._computeParticleVertex) {
  61628. this.updateParticleVertex(this._particle, this._vertex, pt);
  61629. }
  61630. // positions
  61631. this._vertex.x *= this._particle.scaling.x;
  61632. this._vertex.y *= this._particle.scaling.y;
  61633. this._vertex.z *= this._particle.scaling.z;
  61634. this._vertex.x -= this._scaledPivot.x;
  61635. this._vertex.y -= this._scaledPivot.y;
  61636. this._vertex.z -= this._scaledPivot.z;
  61637. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61638. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61639. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61640. this._rotated.x += this._pivotBackTranslation.x;
  61641. this._rotated.y += this._pivotBackTranslation.y;
  61642. this._rotated.z += this._pivotBackTranslation.z;
  61643. 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;
  61644. 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;
  61645. 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;
  61646. if (this._computeBoundingBox) {
  61647. if (this._positions32[idx] < this._minimum.x) {
  61648. this._minimum.x = this._positions32[idx];
  61649. }
  61650. if (this._positions32[idx] > this._maximum.x) {
  61651. this._maximum.x = this._positions32[idx];
  61652. }
  61653. if (this._positions32[idx + 1] < this._minimum.y) {
  61654. this._minimum.y = this._positions32[idx + 1];
  61655. }
  61656. if (this._positions32[idx + 1] > this._maximum.y) {
  61657. this._maximum.y = this._positions32[idx + 1];
  61658. }
  61659. if (this._positions32[idx + 2] < this._minimum.z) {
  61660. this._minimum.z = this._positions32[idx + 2];
  61661. }
  61662. if (this._positions32[idx + 2] > this._maximum.z) {
  61663. this._maximum.z = this._positions32[idx + 2];
  61664. }
  61665. }
  61666. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  61667. if (!this._computeParticleVertex) {
  61668. this._normal.x = this._fixedNormal32[idx];
  61669. this._normal.y = this._fixedNormal32[idx + 1];
  61670. this._normal.z = this._fixedNormal32[idx + 2];
  61671. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  61672. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  61673. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  61674. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61675. 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;
  61676. 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;
  61677. }
  61678. if (this._computeParticleColor && this._particle.color) {
  61679. this._colors32[colidx] = this._particle.color.r;
  61680. this._colors32[colidx + 1] = this._particle.color.g;
  61681. this._colors32[colidx + 2] = this._particle.color.b;
  61682. this._colors32[colidx + 3] = this._particle.color.a;
  61683. }
  61684. if (this._computeParticleTexture) {
  61685. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61686. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61687. }
  61688. }
  61689. }
  61690. // particle just set invisible : scaled to zero and positioned at the origin
  61691. else {
  61692. this._particle._stillInvisible = true; // mark the particle as invisible
  61693. for (pt = 0; pt < this._shape.length; pt++) {
  61694. idx = index + pt * 3;
  61695. colidx = colorIndex + pt * 4;
  61696. uvidx = uvIndex + pt * 2;
  61697. this._positions32[idx] = 0.0;
  61698. this._positions32[idx + 1] = 0.0;
  61699. this._positions32[idx + 2] = 0.0;
  61700. this._normals32[idx] = 0.0;
  61701. this._normals32[idx + 1] = 0.0;
  61702. this._normals32[idx + 2] = 0.0;
  61703. if (this._computeParticleColor && this._particle.color) {
  61704. this._colors32[colidx] = this._particle.color.r;
  61705. this._colors32[colidx + 1] = this._particle.color.g;
  61706. this._colors32[colidx + 2] = this._particle.color.b;
  61707. this._colors32[colidx + 3] = this._particle.color.a;
  61708. }
  61709. if (this._computeParticleTexture) {
  61710. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61711. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61712. }
  61713. }
  61714. }
  61715. // if the particle intersections must be computed : update the bbInfo
  61716. if (this._particlesIntersect) {
  61717. var bInfo = this._particle._boundingInfo;
  61718. var bBox = bInfo.boundingBox;
  61719. var bSphere = bInfo.boundingSphere;
  61720. if (!this._bSphereOnly) {
  61721. // place, scale and rotate the particle bbox within the SPS local system, then update it
  61722. for (var b = 0; b < bBox.vectors.length; b++) {
  61723. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  61724. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  61725. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  61726. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61727. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61728. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61729. 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;
  61730. 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;
  61731. 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;
  61732. }
  61733. bBox._update(this.mesh._worldMatrix);
  61734. }
  61735. // place and scale the particle bouding sphere in the SPS local system, then update it
  61736. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  61737. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  61738. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  61739. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  61740. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  61741. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  61742. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  61743. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  61744. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  61745. 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));
  61746. bSphere._update(this.mesh._worldMatrix);
  61747. }
  61748. // increment indexes for the next particle
  61749. index = idx + 3;
  61750. colorIndex = colidx + 4;
  61751. uvIndex = uvidx + 2;
  61752. }
  61753. // if the VBO must be updated
  61754. if (update) {
  61755. if (this._computeParticleColor) {
  61756. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  61757. }
  61758. if (this._computeParticleTexture) {
  61759. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  61760. }
  61761. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61762. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  61763. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  61764. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  61765. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  61766. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  61767. for (var i = 0; i < this._normals32.length; i++) {
  61768. this._fixedNormal32[i] = this._normals32[i];
  61769. }
  61770. }
  61771. if (!this.mesh.areNormalsFrozen) {
  61772. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  61773. }
  61774. }
  61775. if (this._depthSort && this._depthSortParticles) {
  61776. this.depthSortedParticles.sort(this._depthSortFunction);
  61777. var dspl = this.depthSortedParticles.length;
  61778. var sorted = 0;
  61779. var lind = 0;
  61780. var sind = 0;
  61781. var sid = 0;
  61782. for (sorted = 0; sorted < dspl; sorted++) {
  61783. lind = this.depthSortedParticles[sorted].indicesLength;
  61784. sind = this.depthSortedParticles[sorted].ind;
  61785. for (var i = 0; i < lind; i++) {
  61786. this._indices32[sid] = this._indices[sind + i];
  61787. sid++;
  61788. }
  61789. }
  61790. this.mesh.updateIndices(this._indices32);
  61791. }
  61792. }
  61793. if (this._computeBoundingBox) {
  61794. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  61795. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  61796. }
  61797. this.afterUpdateParticles(start, end, update);
  61798. return this;
  61799. };
  61800. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  61801. this._halfroll = this._roll * 0.5;
  61802. this._halfpitch = this._pitch * 0.5;
  61803. this._halfyaw = this._yaw * 0.5;
  61804. this._sinRoll = Math.sin(this._halfroll);
  61805. this._cosRoll = Math.cos(this._halfroll);
  61806. this._sinPitch = Math.sin(this._halfpitch);
  61807. this._cosPitch = Math.cos(this._halfpitch);
  61808. this._sinYaw = Math.sin(this._halfyaw);
  61809. this._cosYaw = Math.cos(this._halfyaw);
  61810. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  61811. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  61812. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  61813. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  61814. };
  61815. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  61816. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  61817. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  61818. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  61819. this._rotMatrix.m[3] = 0;
  61820. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  61821. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  61822. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  61823. this._rotMatrix.m[7] = 0;
  61824. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  61825. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  61826. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  61827. this._rotMatrix.m[11] = 0;
  61828. this._rotMatrix.m[12] = 0;
  61829. this._rotMatrix.m[13] = 0;
  61830. this._rotMatrix.m[14] = 0;
  61831. this._rotMatrix.m[15] = 1.0;
  61832. };
  61833. /**
  61834. * Disposes the SPS.
  61835. */
  61836. SolidParticleSystem.prototype.dispose = function () {
  61837. this.mesh.dispose();
  61838. this.vars = null;
  61839. // drop references to internal big arrays for the GC
  61840. this._positions = null;
  61841. this._indices = null;
  61842. this._normals = null;
  61843. this._uvs = null;
  61844. this._colors = null;
  61845. this._indices32 = null;
  61846. this._positions32 = null;
  61847. this._normals32 = null;
  61848. this._fixedNormal32 = null;
  61849. this._uvs32 = null;
  61850. this._colors32 = null;
  61851. this.pickedParticles = null;
  61852. };
  61853. /**
  61854. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  61855. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61856. * @returns the SPS.
  61857. */
  61858. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  61859. if (!this._isVisibilityBoxLocked) {
  61860. this.mesh.refreshBoundingInfo();
  61861. }
  61862. return this;
  61863. };
  61864. /**
  61865. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  61866. * @param size the size (float) of the visibility box
  61867. * note : this doesn't lock the SPS mesh bounding box.
  61868. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61869. */
  61870. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  61871. var vis = size / 2;
  61872. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  61873. };
  61874. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  61875. /**
  61876. * Gets whether the SPS as always visible or not
  61877. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61878. */
  61879. get: function () {
  61880. return this._alwaysVisible;
  61881. },
  61882. /**
  61883. * Sets the SPS as always visible or not
  61884. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61885. */
  61886. set: function (val) {
  61887. this._alwaysVisible = val;
  61888. this.mesh.alwaysSelectAsActiveMesh = val;
  61889. },
  61890. enumerable: true,
  61891. configurable: true
  61892. });
  61893. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  61894. /**
  61895. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61896. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61897. */
  61898. get: function () {
  61899. return this._isVisibilityBoxLocked;
  61900. },
  61901. /**
  61902. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61903. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61904. */
  61905. set: function (val) {
  61906. this._isVisibilityBoxLocked = val;
  61907. var boundingInfo = this.mesh.getBoundingInfo();
  61908. boundingInfo.isLocked = val;
  61909. },
  61910. enumerable: true,
  61911. configurable: true
  61912. });
  61913. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  61914. /**
  61915. * Gets if `setParticles()` computes the particle rotations or not.
  61916. * Default value : true. The SPS is faster when it's set to false.
  61917. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61918. */
  61919. get: function () {
  61920. return this._computeParticleRotation;
  61921. },
  61922. /**
  61923. * Tells to `setParticles()` to compute the particle rotations or not.
  61924. * Default value : true. The SPS is faster when it's set to false.
  61925. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61926. */
  61927. set: function (val) {
  61928. this._computeParticleRotation = val;
  61929. },
  61930. enumerable: true,
  61931. configurable: true
  61932. });
  61933. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  61934. /**
  61935. * Gets if `setParticles()` computes the particle colors or not.
  61936. * Default value : true. The SPS is faster when it's set to false.
  61937. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61938. */
  61939. get: function () {
  61940. return this._computeParticleColor;
  61941. },
  61942. /**
  61943. * Tells to `setParticles()` to compute the particle colors or not.
  61944. * Default value : true. The SPS is faster when it's set to false.
  61945. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61946. */
  61947. set: function (val) {
  61948. this._computeParticleColor = val;
  61949. },
  61950. enumerable: true,
  61951. configurable: true
  61952. });
  61953. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  61954. /**
  61955. * Gets if `setParticles()` computes the particle textures or not.
  61956. * Default value : true. The SPS is faster when it's set to false.
  61957. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  61958. */
  61959. get: function () {
  61960. return this._computeParticleTexture;
  61961. },
  61962. set: function (val) {
  61963. this._computeParticleTexture = val;
  61964. },
  61965. enumerable: true,
  61966. configurable: true
  61967. });
  61968. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  61969. /**
  61970. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  61971. * Default value : false. The SPS is faster when it's set to false.
  61972. * Note : the particle custom vertex positions aren't stored values.
  61973. */
  61974. get: function () {
  61975. return this._computeParticleVertex;
  61976. },
  61977. /**
  61978. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  61979. * Default value : false. The SPS is faster when it's set to false.
  61980. * Note : the particle custom vertex positions aren't stored values.
  61981. */
  61982. set: function (val) {
  61983. this._computeParticleVertex = val;
  61984. },
  61985. enumerable: true,
  61986. configurable: true
  61987. });
  61988. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  61989. /**
  61990. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  61991. */
  61992. get: function () {
  61993. return this._computeBoundingBox;
  61994. },
  61995. /**
  61996. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  61997. */
  61998. set: function (val) {
  61999. this._computeBoundingBox = val;
  62000. },
  62001. enumerable: true,
  62002. configurable: true
  62003. });
  62004. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  62005. /**
  62006. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  62007. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62008. * Default : `true`
  62009. */
  62010. get: function () {
  62011. return this._depthSortParticles;
  62012. },
  62013. /**
  62014. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  62015. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62016. * Default : `true`
  62017. */
  62018. set: function (val) {
  62019. this._depthSortParticles = val;
  62020. },
  62021. enumerable: true,
  62022. configurable: true
  62023. });
  62024. // =======================================================================
  62025. // Particle behavior logic
  62026. // these following methods may be overwritten by the user to fit his needs
  62027. /**
  62028. * This function does nothing. It may be overwritten to set all the particle first values.
  62029. * The SPS doesn't call this function, you may have to call it by your own.
  62030. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62031. */
  62032. SolidParticleSystem.prototype.initParticles = function () {
  62033. };
  62034. /**
  62035. * This function does nothing. It may be overwritten to recycle a particle.
  62036. * The SPS doesn't call this function, you may have to call it by your own.
  62037. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62038. * @param particle The particle to recycle
  62039. * @returns the recycled particle
  62040. */
  62041. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  62042. return particle;
  62043. };
  62044. /**
  62045. * Updates a particle : this function should be overwritten by the user.
  62046. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  62047. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62048. * @example : just set a particle position or velocity and recycle conditions
  62049. * @param particle The particle to update
  62050. * @returns the updated particle
  62051. */
  62052. SolidParticleSystem.prototype.updateParticle = function (particle) {
  62053. return particle;
  62054. };
  62055. /**
  62056. * Updates a vertex of a particle : it can be overwritten by the user.
  62057. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  62058. * @param particle the current particle
  62059. * @param vertex the current index of the current particle
  62060. * @param pt the index of the current vertex in the particle shape
  62061. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  62062. * @example : just set a vertex particle position
  62063. * @returns the updated vertex
  62064. */
  62065. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  62066. return vertex;
  62067. };
  62068. /**
  62069. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  62070. * This does nothing and may be overwritten by the user.
  62071. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62072. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62073. * @param update the boolean update value actually passed to setParticles()
  62074. */
  62075. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  62076. };
  62077. /**
  62078. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  62079. * This will be passed three parameters.
  62080. * This does nothing and may be overwritten by the user.
  62081. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62082. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62083. * @param update the boolean update value actually passed to setParticles()
  62084. */
  62085. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  62086. };
  62087. return SolidParticleSystem;
  62088. }());
  62089. BABYLON.SolidParticleSystem = SolidParticleSystem;
  62090. })(BABYLON || (BABYLON = {}));
  62091. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  62092. var BABYLON;
  62093. (function (BABYLON) {
  62094. /**
  62095. * Class containing static functions to help procedurally build meshes
  62096. */
  62097. var MeshBuilder = /** @class */ (function () {
  62098. function MeshBuilder() {
  62099. }
  62100. MeshBuilder.updateSideOrientation = function (orientation) {
  62101. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62102. return BABYLON.Mesh.DOUBLESIDE;
  62103. }
  62104. if (orientation === undefined || orientation === null) {
  62105. return BABYLON.Mesh.FRONTSIDE;
  62106. }
  62107. return orientation;
  62108. };
  62109. /**
  62110. * Creates a box mesh
  62111. * * The parameter `size` sets the size (float) of each box side (default 1)
  62112. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  62113. * * 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)
  62114. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62115. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62116. * * 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
  62117. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62118. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  62119. * @param name defines the name of the mesh
  62120. * @param options defines the options used to create the mesh
  62121. * @param scene defines the hosting scene
  62122. * @returns the box mesh
  62123. */
  62124. MeshBuilder.CreateBox = function (name, options, scene) {
  62125. if (scene === void 0) { scene = null; }
  62126. var box = new BABYLON.Mesh(name, scene);
  62127. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62128. box._originalBuilderSideOrientation = options.sideOrientation;
  62129. var vertexData = BABYLON.VertexData.CreateBox(options);
  62130. vertexData.applyToMesh(box, options.updatable);
  62131. return box;
  62132. };
  62133. /**
  62134. * Creates a sphere mesh
  62135. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  62136. * * 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`)
  62137. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  62138. * * 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
  62139. * * 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)
  62140. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62141. * * 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
  62142. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62143. * @param name defines the name of the mesh
  62144. * @param options defines the options used to create the mesh
  62145. * @param scene defines the hosting scene
  62146. * @returns the sphere mesh
  62147. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  62148. */
  62149. MeshBuilder.CreateSphere = function (name, options, scene) {
  62150. var sphere = new BABYLON.Mesh(name, scene);
  62151. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62152. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62153. var vertexData = BABYLON.VertexData.CreateSphere(options);
  62154. vertexData.applyToMesh(sphere, options.updatable);
  62155. return sphere;
  62156. };
  62157. /**
  62158. * Creates a plane polygonal mesh. By default, this is a disc
  62159. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  62160. * * 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
  62161. * * 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
  62162. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62163. * * 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
  62164. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62165. * @param name defines the name of the mesh
  62166. * @param options defines the options used to create the mesh
  62167. * @param scene defines the hosting scene
  62168. * @returns the plane polygonal mesh
  62169. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  62170. */
  62171. MeshBuilder.CreateDisc = function (name, options, scene) {
  62172. if (scene === void 0) { scene = null; }
  62173. var disc = new BABYLON.Mesh(name, scene);
  62174. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62175. disc._originalBuilderSideOrientation = options.sideOrientation;
  62176. var vertexData = BABYLON.VertexData.CreateDisc(options);
  62177. vertexData.applyToMesh(disc, options.updatable);
  62178. return disc;
  62179. };
  62180. /**
  62181. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  62182. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  62183. * * 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`)
  62184. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  62185. * * 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
  62186. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62187. * * 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
  62188. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62189. * @param name defines the name of the mesh
  62190. * @param options defines the options used to create the mesh
  62191. * @param scene defines the hosting scene
  62192. * @returns the icosahedron mesh
  62193. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  62194. */
  62195. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  62196. var sphere = new BABYLON.Mesh(name, scene);
  62197. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62198. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62199. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  62200. vertexData.applyToMesh(sphere, options.updatable);
  62201. return sphere;
  62202. };
  62203. ;
  62204. /**
  62205. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62206. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  62207. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  62208. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  62209. * * 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
  62210. * * 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
  62211. * * 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
  62212. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62213. * * 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
  62214. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62215. * * 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
  62216. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  62217. * * 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
  62218. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  62219. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62220. * @param name defines the name of the mesh
  62221. * @param options defines the options used to create the mesh
  62222. * @param scene defines the hosting scene
  62223. * @returns the ribbon mesh
  62224. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  62225. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62226. */
  62227. MeshBuilder.CreateRibbon = function (name, options, scene) {
  62228. if (scene === void 0) { scene = null; }
  62229. var pathArray = options.pathArray;
  62230. var closeArray = options.closeArray;
  62231. var closePath = options.closePath;
  62232. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62233. var instance = options.instance;
  62234. var updatable = options.updatable;
  62235. if (instance) { // existing ribbon instance update
  62236. // positionFunction : ribbon case
  62237. // only pathArray and sideOrientation parameters are taken into account for positions update
  62238. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  62239. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  62240. var positionFunction = function (positions) {
  62241. var minlg = pathArray[0].length;
  62242. var i = 0;
  62243. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  62244. for (var si = 1; si <= ns; si++) {
  62245. for (var p = 0; p < pathArray.length; p++) {
  62246. var path = pathArray[p];
  62247. var l = path.length;
  62248. minlg = (minlg < l) ? minlg : l;
  62249. var j = 0;
  62250. while (j < minlg) {
  62251. positions[i] = path[j].x;
  62252. positions[i + 1] = path[j].y;
  62253. positions[i + 2] = path[j].z;
  62254. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  62255. BABYLON.Tmp.Vector3[0].x = path[j].x;
  62256. }
  62257. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  62258. BABYLON.Tmp.Vector3[1].x = path[j].x;
  62259. }
  62260. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  62261. BABYLON.Tmp.Vector3[0].y = path[j].y;
  62262. }
  62263. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  62264. BABYLON.Tmp.Vector3[1].y = path[j].y;
  62265. }
  62266. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  62267. BABYLON.Tmp.Vector3[0].z = path[j].z;
  62268. }
  62269. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  62270. BABYLON.Tmp.Vector3[1].z = path[j].z;
  62271. }
  62272. j++;
  62273. i += 3;
  62274. }
  62275. if (instance._closePath) {
  62276. positions[i] = path[0].x;
  62277. positions[i + 1] = path[0].y;
  62278. positions[i + 2] = path[0].z;
  62279. i += 3;
  62280. }
  62281. }
  62282. }
  62283. };
  62284. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62285. positionFunction(positions);
  62286. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  62287. instance._boundingInfo.update(instance._worldMatrix);
  62288. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62289. if (options.colors) {
  62290. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62291. for (var c = 0; c < options.colors.length; c++) {
  62292. colors[c * 4] = options.colors[c].r;
  62293. colors[c * 4 + 1] = options.colors[c].g;
  62294. colors[c * 4 + 2] = options.colors[c].b;
  62295. colors[c * 4 + 3] = options.colors[c].a;
  62296. }
  62297. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  62298. }
  62299. if (options.uvs) {
  62300. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62301. for (var i = 0; i < options.uvs.length; i++) {
  62302. uvs[i * 2] = options.uvs[i].x;
  62303. uvs[i * 2 + 1] = options.uvs[i].y;
  62304. }
  62305. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  62306. }
  62307. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  62308. var indices = instance.getIndices();
  62309. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62310. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  62311. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  62312. if (instance._closePath) {
  62313. var indexFirst = 0;
  62314. var indexLast = 0;
  62315. for (var p = 0; p < pathArray.length; p++) {
  62316. indexFirst = instance._idx[p] * 3;
  62317. if (p + 1 < pathArray.length) {
  62318. indexLast = (instance._idx[p + 1] - 1) * 3;
  62319. }
  62320. else {
  62321. indexLast = normals.length - 3;
  62322. }
  62323. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  62324. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  62325. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  62326. normals[indexLast] = normals[indexFirst];
  62327. normals[indexLast + 1] = normals[indexFirst + 1];
  62328. normals[indexLast + 2] = normals[indexFirst + 2];
  62329. }
  62330. }
  62331. if (!(instance.areNormalsFrozen)) {
  62332. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  62333. }
  62334. }
  62335. return instance;
  62336. }
  62337. else { // new ribbon creation
  62338. var ribbon = new BABYLON.Mesh(name, scene);
  62339. ribbon._originalBuilderSideOrientation = sideOrientation;
  62340. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  62341. if (closePath) {
  62342. ribbon._idx = vertexData._idx;
  62343. }
  62344. ribbon._closePath = closePath;
  62345. ribbon._closeArray = closeArray;
  62346. vertexData.applyToMesh(ribbon, updatable);
  62347. return ribbon;
  62348. }
  62349. };
  62350. /**
  62351. * Creates a cylinder or a cone mesh
  62352. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  62353. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  62354. * * 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.
  62355. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  62356. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  62357. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  62358. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  62359. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  62360. * * 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).
  62361. * * 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
  62362. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  62363. * * 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
  62364. * * 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.
  62365. * * If `enclose` is false, a ring surface is one element.
  62366. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  62367. * * 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
  62368. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62369. * * 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
  62370. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62371. * @param name defines the name of the mesh
  62372. * @param options defines the options used to create the mesh
  62373. * @param scene defines the hosting scene
  62374. * @returns the cylinder mesh
  62375. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  62376. */
  62377. MeshBuilder.CreateCylinder = function (name, options, scene) {
  62378. var cylinder = new BABYLON.Mesh(name, scene);
  62379. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62380. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  62381. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  62382. vertexData.applyToMesh(cylinder, options.updatable);
  62383. return cylinder;
  62384. };
  62385. /**
  62386. * Creates a torus mesh
  62387. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  62388. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  62389. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  62390. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62391. * * 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
  62392. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62393. * @param name defines the name of the mesh
  62394. * @param options defines the options used to create the mesh
  62395. * @param scene defines the hosting scene
  62396. * @returns the torus mesh
  62397. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  62398. */
  62399. MeshBuilder.CreateTorus = function (name, options, scene) {
  62400. var torus = new BABYLON.Mesh(name, scene);
  62401. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62402. torus._originalBuilderSideOrientation = options.sideOrientation;
  62403. var vertexData = BABYLON.VertexData.CreateTorus(options);
  62404. vertexData.applyToMesh(torus, options.updatable);
  62405. return torus;
  62406. };
  62407. /**
  62408. * Creates a torus knot mesh
  62409. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  62410. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  62411. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  62412. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  62413. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62414. * * 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
  62415. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62416. * @param name defines the name of the mesh
  62417. * @param options defines the options used to create the mesh
  62418. * @param scene defines the hosting scene
  62419. * @returns the torus knot mesh
  62420. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  62421. */
  62422. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  62423. var torusKnot = new BABYLON.Mesh(name, scene);
  62424. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62425. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  62426. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  62427. vertexData.applyToMesh(torusKnot, options.updatable);
  62428. return torusKnot;
  62429. };
  62430. /**
  62431. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  62432. * * 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
  62433. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  62434. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  62435. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  62436. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  62437. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  62438. * * 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
  62439. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  62440. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62441. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  62442. * @param name defines the name of the new line system
  62443. * @param options defines the options used to create the line system
  62444. * @param scene defines the hosting scene
  62445. * @returns a new line system mesh
  62446. */
  62447. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  62448. var instance = options.instance;
  62449. var lines = options.lines;
  62450. var colors = options.colors;
  62451. if (instance) { // lines update
  62452. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62453. var vertexColor;
  62454. var lineColors;
  62455. if (colors) {
  62456. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62457. }
  62458. var i = 0;
  62459. var c = 0;
  62460. for (var l = 0; l < lines.length; l++) {
  62461. var points = lines[l];
  62462. for (var p = 0; p < points.length; p++) {
  62463. positions[i] = points[p].x;
  62464. positions[i + 1] = points[p].y;
  62465. positions[i + 2] = points[p].z;
  62466. if (colors && vertexColor) {
  62467. lineColors = colors[l];
  62468. vertexColor[c] = lineColors[p].r;
  62469. vertexColor[c + 1] = lineColors[p].g;
  62470. vertexColor[c + 2] = lineColors[p].b;
  62471. vertexColor[c + 3] = lineColors[p].a;
  62472. c += 4;
  62473. }
  62474. i += 3;
  62475. }
  62476. }
  62477. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62478. if (colors && vertexColor) {
  62479. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  62480. }
  62481. return instance;
  62482. }
  62483. // line system creation
  62484. var useVertexColor = (colors) ? true : false;
  62485. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  62486. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  62487. vertexData.applyToMesh(lineSystem, options.updatable);
  62488. return lineSystem;
  62489. };
  62490. /**
  62491. * Creates a line mesh
  62492. * 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
  62493. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62494. * * The parameter `points` is an array successive Vector3
  62495. * * 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
  62496. * * The optional parameter `colors` is an array of successive Color4, one per line point
  62497. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  62498. * * When updating an instance, remember that only point positions can change, not the number of points
  62499. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62500. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  62501. * @param name defines the name of the new line system
  62502. * @param options defines the options used to create the line system
  62503. * @param scene defines the hosting scene
  62504. * @returns a new line mesh
  62505. */
  62506. MeshBuilder.CreateLines = function (name, options, scene) {
  62507. if (scene === void 0) { scene = null; }
  62508. var colors = (options.colors) ? [options.colors] : null;
  62509. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  62510. return lines;
  62511. };
  62512. /**
  62513. * Creates a dashed line mesh
  62514. * * 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
  62515. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62516. * * The parameter `points` is an array successive Vector3
  62517. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  62518. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  62519. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  62520. * * 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
  62521. * * When updating an instance, remember that only point positions can change, not the number of points
  62522. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62523. * @param name defines the name of the mesh
  62524. * @param options defines the options used to create the mesh
  62525. * @param scene defines the hosting scene
  62526. * @returns the dashed line mesh
  62527. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  62528. */
  62529. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  62530. if (scene === void 0) { scene = null; }
  62531. var points = options.points;
  62532. var instance = options.instance;
  62533. var gapSize = options.gapSize || 1;
  62534. var dashSize = options.dashSize || 3;
  62535. if (instance) { // dashed lines update
  62536. var positionFunction = function (positions) {
  62537. var curvect = BABYLON.Vector3.Zero();
  62538. var nbSeg = positions.length / 6;
  62539. var lg = 0;
  62540. var nb = 0;
  62541. var shft = 0;
  62542. var dashshft = 0;
  62543. var curshft = 0;
  62544. var p = 0;
  62545. var i = 0;
  62546. var j = 0;
  62547. for (i = 0; i < points.length - 1; i++) {
  62548. points[i + 1].subtractToRef(points[i], curvect);
  62549. lg += curvect.length();
  62550. }
  62551. shft = lg / nbSeg;
  62552. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  62553. for (i = 0; i < points.length - 1; i++) {
  62554. points[i + 1].subtractToRef(points[i], curvect);
  62555. nb = Math.floor(curvect.length() / shft);
  62556. curvect.normalize();
  62557. j = 0;
  62558. while (j < nb && p < positions.length) {
  62559. curshft = shft * j;
  62560. positions[p] = points[i].x + curshft * curvect.x;
  62561. positions[p + 1] = points[i].y + curshft * curvect.y;
  62562. positions[p + 2] = points[i].z + curshft * curvect.z;
  62563. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  62564. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  62565. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  62566. p += 6;
  62567. j++;
  62568. }
  62569. }
  62570. while (p < positions.length) {
  62571. positions[p] = points[i].x;
  62572. positions[p + 1] = points[i].y;
  62573. positions[p + 2] = points[i].z;
  62574. p += 3;
  62575. }
  62576. };
  62577. instance.updateMeshPositions(positionFunction, false);
  62578. return instance;
  62579. }
  62580. // dashed lines creation
  62581. var dashedLines = new BABYLON.LinesMesh(name, scene);
  62582. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  62583. vertexData.applyToMesh(dashedLines, options.updatable);
  62584. dashedLines.dashSize = dashSize;
  62585. dashedLines.gapSize = gapSize;
  62586. return dashedLines;
  62587. };
  62588. /**
  62589. * 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.
  62590. * * 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.
  62591. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62592. * * 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.
  62593. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  62594. * * 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
  62595. * * 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
  62596. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  62597. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62598. * * 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
  62599. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  62600. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62601. * @param name defines the name of the mesh
  62602. * @param options defines the options used to create the mesh
  62603. * @param scene defines the hosting scene
  62604. * @returns the extruded shape mesh
  62605. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62606. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62607. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62608. */
  62609. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  62610. if (scene === void 0) { scene = null; }
  62611. var path = options.path;
  62612. var shape = options.shape;
  62613. var scale = options.scale || 1;
  62614. var rotation = options.rotation || 0;
  62615. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62616. var updatable = options.updatable;
  62617. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62618. var instance = options.instance || null;
  62619. var invertUV = options.invertUV || false;
  62620. 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);
  62621. };
  62622. /**
  62623. * Creates an custom extruded shape mesh.
  62624. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62625. * * 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.
  62626. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62627. * * 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
  62628. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  62629. * * 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
  62630. * * It must returns a float value that will be the scale value applied to the shape on each path point
  62631. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  62632. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  62633. * * 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
  62634. * * 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
  62635. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  62636. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62637. * * 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
  62638. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62639. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62640. * @param name defines the name of the mesh
  62641. * @param options defines the options used to create the mesh
  62642. * @param scene defines the hosting scene
  62643. * @returns the custom extruded shape mesh
  62644. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  62645. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62646. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62647. */
  62648. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  62649. var path = options.path;
  62650. var shape = options.shape;
  62651. var scaleFunction = options.scaleFunction || (function () { return 1; });
  62652. var rotationFunction = options.rotationFunction || (function () { return 0; });
  62653. var ribbonCloseArray = options.ribbonCloseArray || false;
  62654. var ribbonClosePath = options.ribbonClosePath || false;
  62655. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62656. var updatable = options.updatable;
  62657. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62658. var instance = options.instance;
  62659. var invertUV = options.invertUV || false;
  62660. 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);
  62661. };
  62662. /**
  62663. * Creates lathe mesh.
  62664. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  62665. * * 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
  62666. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  62667. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  62668. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  62669. * * 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
  62670. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  62671. * * 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
  62672. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62673. * * 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
  62674. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62675. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62676. * @param name defines the name of the mesh
  62677. * @param options defines the options used to create the mesh
  62678. * @param scene defines the hosting scene
  62679. * @returns the lathe mesh
  62680. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  62681. */
  62682. MeshBuilder.CreateLathe = function (name, options, scene) {
  62683. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  62684. var closed = (options.closed === undefined) ? true : options.closed;
  62685. var shape = options.shape;
  62686. var radius = options.radius || 1;
  62687. var tessellation = options.tessellation || 64;
  62688. var clip = options.clip || 0;
  62689. var updatable = options.updatable;
  62690. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62691. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62692. var pi2 = Math.PI * 2;
  62693. var paths = new Array();
  62694. var invertUV = options.invertUV || false;
  62695. var i = 0;
  62696. var p = 0;
  62697. var step = pi2 / tessellation * arc;
  62698. var rotated;
  62699. var path = new Array();
  62700. for (i = 0; i <= tessellation - clip; i++) {
  62701. var path = [];
  62702. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  62703. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  62704. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  62705. }
  62706. for (p = 0; p < shape.length; p++) {
  62707. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  62708. path.push(rotated);
  62709. }
  62710. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  62711. 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));
  62712. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  62713. }
  62714. paths.push(path);
  62715. }
  62716. // lathe ribbon
  62717. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62718. return lathe;
  62719. };
  62720. /**
  62721. * Creates a plane mesh
  62722. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  62723. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  62724. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  62725. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62726. * * 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
  62727. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62728. * @param name defines the name of the mesh
  62729. * @param options defines the options used to create the mesh
  62730. * @param scene defines the hosting scene
  62731. * @returns the plane mesh
  62732. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62733. */
  62734. MeshBuilder.CreatePlane = function (name, options, scene) {
  62735. var plane = new BABYLON.Mesh(name, scene);
  62736. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62737. plane._originalBuilderSideOrientation = options.sideOrientation;
  62738. var vertexData = BABYLON.VertexData.CreatePlane(options);
  62739. vertexData.applyToMesh(plane, options.updatable);
  62740. if (options.sourcePlane) {
  62741. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  62742. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  62743. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  62744. plane.rotate(vectorProduct, product);
  62745. }
  62746. return plane;
  62747. };
  62748. /**
  62749. * Creates a ground mesh
  62750. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  62751. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  62752. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62753. * @param name defines the name of the mesh
  62754. * @param options defines the options used to create the mesh
  62755. * @param scene defines the hosting scene
  62756. * @returns the ground mesh
  62757. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62758. */
  62759. MeshBuilder.CreateGround = function (name, options, scene) {
  62760. var ground = new BABYLON.GroundMesh(name, scene);
  62761. ground._setReady(false);
  62762. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  62763. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  62764. ground._width = options.width || 1;
  62765. ground._height = options.height || 1;
  62766. ground._maxX = ground._width / 2;
  62767. ground._maxZ = ground._height / 2;
  62768. ground._minX = -ground._maxX;
  62769. ground._minZ = -ground._maxZ;
  62770. var vertexData = BABYLON.VertexData.CreateGround(options);
  62771. vertexData.applyToMesh(ground, options.updatable);
  62772. ground._setReady(true);
  62773. return ground;
  62774. };
  62775. /**
  62776. * Creates a tiled ground mesh
  62777. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  62778. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  62779. * * 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
  62780. * * 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
  62781. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62782. * @param name defines the name of the mesh
  62783. * @param options defines the options used to create the mesh
  62784. * @param scene defines the hosting scene
  62785. * @returns the tiled ground mesh
  62786. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  62787. */
  62788. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  62789. var tiledGround = new BABYLON.Mesh(name, scene);
  62790. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  62791. vertexData.applyToMesh(tiledGround, options.updatable);
  62792. return tiledGround;
  62793. };
  62794. /**
  62795. * Creates a ground mesh from a height map
  62796. * * The parameter `url` sets the URL of the height map image resource.
  62797. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  62798. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  62799. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  62800. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  62801. * * 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.
  62802. * * 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).
  62803. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62804. * @param name defines the name of the mesh
  62805. * @param url defines the url to the height map
  62806. * @param options defines the options used to create the mesh
  62807. * @param scene defines the hosting scene
  62808. * @returns the ground mesh
  62809. * @see http://doc.babylonjs.com/babylon101/height_map
  62810. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  62811. */
  62812. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  62813. var width = options.width || 10.0;
  62814. var height = options.height || 10.0;
  62815. var subdivisions = options.subdivisions || 1 | 0;
  62816. var minHeight = options.minHeight || 0.0;
  62817. var maxHeight = options.maxHeight || 1.0;
  62818. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  62819. var updatable = options.updatable;
  62820. var onReady = options.onReady;
  62821. var ground = new BABYLON.GroundMesh(name, scene);
  62822. ground._subdivisionsX = subdivisions;
  62823. ground._subdivisionsY = subdivisions;
  62824. ground._width = width;
  62825. ground._height = height;
  62826. ground._maxX = ground._width / 2.0;
  62827. ground._maxZ = ground._height / 2.0;
  62828. ground._minX = -ground._maxX;
  62829. ground._minZ = -ground._maxZ;
  62830. ground._setReady(false);
  62831. var onload = function (img) {
  62832. // Getting height map data
  62833. var canvas = document.createElement("canvas");
  62834. var context = canvas.getContext("2d");
  62835. if (!context) {
  62836. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  62837. }
  62838. if (scene.isDisposed) {
  62839. return;
  62840. }
  62841. var bufferWidth = img.width;
  62842. var bufferHeight = img.height;
  62843. canvas.width = bufferWidth;
  62844. canvas.height = bufferHeight;
  62845. context.drawImage(img, 0, 0);
  62846. // Create VertexData from map data
  62847. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  62848. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  62849. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  62850. width: width, height: height,
  62851. subdivisions: subdivisions,
  62852. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  62853. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  62854. });
  62855. vertexData.applyToMesh(ground, updatable);
  62856. //execute ready callback, if set
  62857. if (onReady) {
  62858. onReady(ground);
  62859. }
  62860. ground._setReady(true);
  62861. };
  62862. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  62863. return ground;
  62864. };
  62865. /**
  62866. * Creates a polygon mesh
  62867. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  62868. * * 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
  62869. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62870. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62871. * * 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)
  62872. * * Remember you can only change the shape positions, not their number when updating a polygon
  62873. * @param name defines the name of the mesh
  62874. * @param options defines the options used to create the mesh
  62875. * @param scene defines the hosting scene
  62876. * @returns the polygon mesh
  62877. */
  62878. MeshBuilder.CreatePolygon = function (name, options, scene) {
  62879. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62880. var shape = options.shape;
  62881. var holes = options.holes || [];
  62882. var depth = options.depth || 0;
  62883. var contours = [];
  62884. var hole = [];
  62885. for (var i = 0; i < shape.length; i++) {
  62886. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  62887. }
  62888. var epsilon = 0.00000001;
  62889. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  62890. contours.pop();
  62891. }
  62892. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  62893. for (var hNb = 0; hNb < holes.length; hNb++) {
  62894. hole = [];
  62895. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  62896. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  62897. }
  62898. polygonTriangulation.addHole(hole);
  62899. }
  62900. var polygon = polygonTriangulation.build(options.updatable, depth);
  62901. polygon._originalBuilderSideOrientation = options.sideOrientation;
  62902. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  62903. vertexData.applyToMesh(polygon, options.updatable);
  62904. return polygon;
  62905. };
  62906. ;
  62907. /**
  62908. * Creates an extruded polygon mesh, with depth in the Y direction.
  62909. * * 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)
  62910. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62911. * @param name defines the name of the mesh
  62912. * @param options defines the options used to create the mesh
  62913. * @param scene defines the hosting scene
  62914. * @returns the polygon mesh
  62915. */
  62916. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  62917. return MeshBuilder.CreatePolygon(name, options, scene);
  62918. };
  62919. ;
  62920. /**
  62921. * Creates a tube mesh.
  62922. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62923. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  62924. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  62925. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  62926. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  62927. * * 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)
  62928. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  62929. * * 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
  62930. * * 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
  62931. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62932. * * 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
  62933. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62934. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62935. * @param name defines the name of the mesh
  62936. * @param options defines the options used to create the mesh
  62937. * @param scene defines the hosting scene
  62938. * @returns the tube mesh
  62939. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62940. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  62941. */
  62942. MeshBuilder.CreateTube = function (name, options, scene) {
  62943. var path = options.path;
  62944. var instance = options.instance;
  62945. var radius = 1.0;
  62946. if (instance) {
  62947. radius = instance.radius;
  62948. }
  62949. if (options.radius !== undefined) {
  62950. radius = options.radius;
  62951. }
  62952. ;
  62953. var tessellation = options.tessellation || 64 | 0;
  62954. var radiusFunction = options.radiusFunction || null;
  62955. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62956. var invertUV = options.invertUV || false;
  62957. var updatable = options.updatable;
  62958. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62959. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  62960. // tube geometry
  62961. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  62962. var tangents = path3D.getTangents();
  62963. var normals = path3D.getNormals();
  62964. var distances = path3D.getDistances();
  62965. var pi2 = Math.PI * 2;
  62966. var step = pi2 / tessellation * arc;
  62967. var returnRadius = function () { return radius; };
  62968. var radiusFunctionFinal = radiusFunction || returnRadius;
  62969. var circlePath;
  62970. var rad;
  62971. var normal;
  62972. var rotated;
  62973. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62974. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62975. for (var i = 0; i < path.length; i++) {
  62976. rad = radiusFunctionFinal(i, distances[i]); // current radius
  62977. circlePath = Array(); // current circle array
  62978. normal = normals[i]; // current normal
  62979. for (var t = 0; t < tessellation; t++) {
  62980. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  62981. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  62982. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  62983. rotated.scaleInPlace(rad).addInPlace(path[i]);
  62984. circlePath[t] = rotated;
  62985. }
  62986. circlePaths[index] = circlePath;
  62987. index++;
  62988. }
  62989. // cap
  62990. var capPath = function (nbPoints, pathIndex) {
  62991. var pointCap = Array();
  62992. for (var i = 0; i < nbPoints; i++) {
  62993. pointCap.push(path[pathIndex]);
  62994. }
  62995. return pointCap;
  62996. };
  62997. switch (cap) {
  62998. case BABYLON.Mesh.NO_CAP:
  62999. break;
  63000. case BABYLON.Mesh.CAP_START:
  63001. circlePaths[0] = capPath(tessellation, 0);
  63002. circlePaths[1] = circlePaths[2].slice(0);
  63003. break;
  63004. case BABYLON.Mesh.CAP_END:
  63005. circlePaths[index] = circlePaths[index - 1].slice(0);
  63006. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63007. break;
  63008. case BABYLON.Mesh.CAP_ALL:
  63009. circlePaths[0] = capPath(tessellation, 0);
  63010. circlePaths[1] = circlePaths[2].slice(0);
  63011. circlePaths[index] = circlePaths[index - 1].slice(0);
  63012. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63013. break;
  63014. default:
  63015. break;
  63016. }
  63017. return circlePaths;
  63018. };
  63019. var path3D;
  63020. var pathArray;
  63021. if (instance) { // tube update
  63022. var arc = options.arc || instance.arc;
  63023. path3D = (instance.path3D).update(path);
  63024. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  63025. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  63026. instance.path3D = path3D;
  63027. instance.pathArray = pathArray;
  63028. instance.arc = arc;
  63029. instance.radius = radius;
  63030. return instance;
  63031. }
  63032. // tube creation
  63033. path3D = new BABYLON.Path3D(path);
  63034. var newPathArray = new Array();
  63035. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63036. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  63037. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63038. tube.pathArray = pathArray;
  63039. tube.path3D = path3D;
  63040. tube.tessellation = tessellation;
  63041. tube.cap = cap;
  63042. tube.arc = options.arc;
  63043. tube.radius = radius;
  63044. return tube;
  63045. };
  63046. /**
  63047. * Creates a polyhedron mesh
  63048. * * 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
  63049. * * The parameter `size` (positive float, default 1) sets the polygon size
  63050. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  63051. * * 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`
  63052. * * 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
  63053. * * 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)`)
  63054. * * 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
  63055. * * 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
  63056. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63057. * * 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
  63058. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63059. * @param name defines the name of the mesh
  63060. * @param options defines the options used to create the mesh
  63061. * @param scene defines the hosting scene
  63062. * @returns the polyhedron mesh
  63063. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  63064. */
  63065. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  63066. var polyhedron = new BABYLON.Mesh(name, scene);
  63067. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63068. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  63069. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  63070. vertexData.applyToMesh(polyhedron, options.updatable);
  63071. return polyhedron;
  63072. };
  63073. /**
  63074. * Creates a decal mesh.
  63075. * 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
  63076. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  63077. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  63078. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  63079. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  63080. * @param name defines the name of the mesh
  63081. * @param sourceMesh defines the mesh where the decal must be applied
  63082. * @param options defines the options used to create the mesh
  63083. * @param scene defines the hosting scene
  63084. * @returns the decal mesh
  63085. * @see http://doc.babylonjs.com/how_to/decals
  63086. */
  63087. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  63088. var indices = sourceMesh.getIndices();
  63089. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63090. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63091. var position = options.position || BABYLON.Vector3.Zero();
  63092. var normal = options.normal || BABYLON.Vector3.Up();
  63093. var size = options.size || BABYLON.Vector3.One();
  63094. var angle = options.angle || 0;
  63095. // Getting correct rotation
  63096. if (!normal) {
  63097. var target = new BABYLON.Vector3(0, 0, 1);
  63098. var camera = sourceMesh.getScene().activeCamera;
  63099. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  63100. normal = camera.globalPosition.subtract(cameraWorldTarget);
  63101. }
  63102. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63103. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63104. var pitch = Math.atan2(normal.y, len);
  63105. // Matrix
  63106. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63107. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63108. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63109. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  63110. var vertexData = new BABYLON.VertexData();
  63111. vertexData.indices = [];
  63112. vertexData.positions = [];
  63113. vertexData.normals = [];
  63114. vertexData.uvs = [];
  63115. var currentVertexDataIndex = 0;
  63116. var extractDecalVector3 = function (indexId) {
  63117. var result = new BABYLON.PositionNormalVertex();
  63118. if (!indices || !positions || !normals) {
  63119. return result;
  63120. }
  63121. var vertexId = indices[indexId];
  63122. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  63123. // Send vector to decal local world
  63124. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  63125. // Get normal
  63126. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  63127. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  63128. return result;
  63129. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  63130. var clip = function (vertices, axis) {
  63131. if (vertices.length === 0) {
  63132. return vertices;
  63133. }
  63134. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  63135. var clipVertices = function (v0, v1) {
  63136. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  63137. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  63138. };
  63139. var result = new Array();
  63140. for (var index = 0; index < vertices.length; index += 3) {
  63141. var v1Out;
  63142. var v2Out;
  63143. var v3Out;
  63144. var total = 0;
  63145. var nV1 = null;
  63146. var nV2 = null;
  63147. var nV3 = null;
  63148. var nV4 = null;
  63149. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  63150. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  63151. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  63152. v1Out = d1 > 0;
  63153. v2Out = d2 > 0;
  63154. v3Out = d3 > 0;
  63155. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  63156. switch (total) {
  63157. case 0:
  63158. result.push(vertices[index]);
  63159. result.push(vertices[index + 1]);
  63160. result.push(vertices[index + 2]);
  63161. break;
  63162. case 1:
  63163. if (v1Out) {
  63164. nV1 = vertices[index + 1];
  63165. nV2 = vertices[index + 2];
  63166. nV3 = clipVertices(vertices[index], nV1);
  63167. nV4 = clipVertices(vertices[index], nV2);
  63168. }
  63169. if (v2Out) {
  63170. nV1 = vertices[index];
  63171. nV2 = vertices[index + 2];
  63172. nV3 = clipVertices(vertices[index + 1], nV1);
  63173. nV4 = clipVertices(vertices[index + 1], nV2);
  63174. result.push(nV3);
  63175. result.push(nV2.clone());
  63176. result.push(nV1.clone());
  63177. result.push(nV2.clone());
  63178. result.push(nV3.clone());
  63179. result.push(nV4);
  63180. break;
  63181. }
  63182. if (v3Out) {
  63183. nV1 = vertices[index];
  63184. nV2 = vertices[index + 1];
  63185. nV3 = clipVertices(vertices[index + 2], nV1);
  63186. nV4 = clipVertices(vertices[index + 2], nV2);
  63187. }
  63188. if (nV1 && nV2 && nV3 && nV4) {
  63189. result.push(nV1.clone());
  63190. result.push(nV2.clone());
  63191. result.push(nV3);
  63192. result.push(nV4);
  63193. result.push(nV3.clone());
  63194. result.push(nV2.clone());
  63195. }
  63196. break;
  63197. case 2:
  63198. if (!v1Out) {
  63199. nV1 = vertices[index].clone();
  63200. nV2 = clipVertices(nV1, vertices[index + 1]);
  63201. nV3 = clipVertices(nV1, vertices[index + 2]);
  63202. result.push(nV1);
  63203. result.push(nV2);
  63204. result.push(nV3);
  63205. }
  63206. if (!v2Out) {
  63207. nV1 = vertices[index + 1].clone();
  63208. nV2 = clipVertices(nV1, vertices[index + 2]);
  63209. nV3 = clipVertices(nV1, vertices[index]);
  63210. result.push(nV1);
  63211. result.push(nV2);
  63212. result.push(nV3);
  63213. }
  63214. if (!v3Out) {
  63215. nV1 = vertices[index + 2].clone();
  63216. nV2 = clipVertices(nV1, vertices[index]);
  63217. nV3 = clipVertices(nV1, vertices[index + 1]);
  63218. result.push(nV1);
  63219. result.push(nV2);
  63220. result.push(nV3);
  63221. }
  63222. break;
  63223. case 3:
  63224. break;
  63225. }
  63226. }
  63227. return result;
  63228. };
  63229. for (var index = 0; index < indices.length; index += 3) {
  63230. var faceVertices = new Array();
  63231. faceVertices.push(extractDecalVector3(index));
  63232. faceVertices.push(extractDecalVector3(index + 1));
  63233. faceVertices.push(extractDecalVector3(index + 2));
  63234. // Clip
  63235. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  63236. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  63237. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  63238. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  63239. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  63240. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  63241. if (faceVertices.length === 0) {
  63242. continue;
  63243. }
  63244. // Add UVs and get back to world
  63245. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  63246. var vertex = faceVertices[vIndex];
  63247. //TODO check for Int32Array | Uint32Array | Uint16Array
  63248. vertexData.indices.push(currentVertexDataIndex);
  63249. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  63250. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  63251. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  63252. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  63253. currentVertexDataIndex++;
  63254. }
  63255. }
  63256. // Return mesh
  63257. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  63258. vertexData.applyToMesh(decal);
  63259. decal.position = position.clone();
  63260. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  63261. return decal;
  63262. };
  63263. // Privates
  63264. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  63265. // extrusion geometry
  63266. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  63267. var tangents = path3D.getTangents();
  63268. var normals = path3D.getNormals();
  63269. var binormals = path3D.getBinormals();
  63270. var distances = path3D.getDistances();
  63271. var angle = 0;
  63272. var returnScale = function () { return scale !== null ? scale : 1; };
  63273. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  63274. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  63275. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  63276. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63277. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63278. for (var i = 0; i < curve.length; i++) {
  63279. var shapePath = new Array();
  63280. var angleStep = rotate(i, distances[i]);
  63281. var scaleRatio = scl(i, distances[i]);
  63282. for (var p = 0; p < shape.length; p++) {
  63283. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  63284. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  63285. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  63286. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  63287. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  63288. shapePath[p] = rotated;
  63289. }
  63290. shapePaths[index] = shapePath;
  63291. angle += angleStep;
  63292. index++;
  63293. }
  63294. // cap
  63295. var capPath = function (shapePath) {
  63296. var pointCap = Array();
  63297. var barycenter = BABYLON.Vector3.Zero();
  63298. var i;
  63299. for (i = 0; i < shapePath.length; i++) {
  63300. barycenter.addInPlace(shapePath[i]);
  63301. }
  63302. barycenter.scaleInPlace(1.0 / shapePath.length);
  63303. for (i = 0; i < shapePath.length; i++) {
  63304. pointCap.push(barycenter);
  63305. }
  63306. return pointCap;
  63307. };
  63308. switch (cap) {
  63309. case BABYLON.Mesh.NO_CAP:
  63310. break;
  63311. case BABYLON.Mesh.CAP_START:
  63312. shapePaths[0] = capPath(shapePaths[2]);
  63313. shapePaths[1] = shapePaths[2];
  63314. break;
  63315. case BABYLON.Mesh.CAP_END:
  63316. shapePaths[index] = shapePaths[index - 1];
  63317. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63318. break;
  63319. case BABYLON.Mesh.CAP_ALL:
  63320. shapePaths[0] = capPath(shapePaths[2]);
  63321. shapePaths[1] = shapePaths[2];
  63322. shapePaths[index] = shapePaths[index - 1];
  63323. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63324. break;
  63325. default:
  63326. break;
  63327. }
  63328. return shapePaths;
  63329. };
  63330. var path3D;
  63331. var pathArray;
  63332. if (instance) { // instance update
  63333. path3D = (instance.path3D).update(curve);
  63334. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  63335. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  63336. return instance;
  63337. }
  63338. // extruded shape creation
  63339. path3D = new BABYLON.Path3D(curve);
  63340. var newShapePaths = new Array();
  63341. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63342. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  63343. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  63344. extrudedGeneric.pathArray = pathArray;
  63345. extrudedGeneric.path3D = path3D;
  63346. extrudedGeneric.cap = cap;
  63347. return extrudedGeneric;
  63348. };
  63349. return MeshBuilder;
  63350. }());
  63351. BABYLON.MeshBuilder = MeshBuilder;
  63352. })(BABYLON || (BABYLON = {}));
  63353. //# sourceMappingURL=babylon.meshBuilder.js.map
  63354. var BABYLON;
  63355. (function (BABYLON) {
  63356. /**
  63357. * Draco compression (https://google.github.io/draco/)
  63358. *
  63359. * This class wraps the Draco module.
  63360. *
  63361. * **Encoder**
  63362. *
  63363. * The encoder is not currently implemented.
  63364. *
  63365. * **Decoder**
  63366. *
  63367. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  63368. *
  63369. * To update the configuration, use the following code:
  63370. * ```javascript
  63371. * BABYLON.DracoCompression.Configuration = {
  63372. * decoder: {
  63373. * wasmUrl: "<url to the WebAssembly library>",
  63374. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  63375. * fallbackUrl: "<url to the fallback JavaScript library>",
  63376. * }
  63377. * };
  63378. * ```
  63379. *
  63380. * 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.
  63381. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  63382. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  63383. *
  63384. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  63385. * ```javascript
  63386. * var dracoCompression = new BABYLON.DracoCompression();
  63387. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  63388. * [BABYLON.VertexBuffer.PositionKind]: 0
  63389. * });
  63390. * ```
  63391. *
  63392. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  63393. */
  63394. var DracoCompression = /** @class */ (function () {
  63395. /**
  63396. * Constructor
  63397. */
  63398. function DracoCompression() {
  63399. }
  63400. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  63401. /**
  63402. * Returns true if the decoder is available.
  63403. */
  63404. get: function () {
  63405. if (typeof DracoDecoderModule !== "undefined") {
  63406. return true;
  63407. }
  63408. var decoder = DracoCompression.Configuration.decoder;
  63409. if (decoder) {
  63410. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63411. return true;
  63412. }
  63413. if (decoder.fallbackUrl) {
  63414. return true;
  63415. }
  63416. }
  63417. return false;
  63418. },
  63419. enumerable: true,
  63420. configurable: true
  63421. });
  63422. /**
  63423. * Stop all async operations and release resources.
  63424. */
  63425. DracoCompression.prototype.dispose = function () {
  63426. };
  63427. /**
  63428. * Decode Draco compressed mesh data to vertex data.
  63429. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  63430. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  63431. * @returns A promise that resolves with the decoded vertex data
  63432. */
  63433. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  63434. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  63435. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  63436. var module = wrappedModule.module;
  63437. var vertexData = new BABYLON.VertexData();
  63438. var buffer = new module.DecoderBuffer();
  63439. buffer.Init(dataView, dataView.byteLength);
  63440. var decoder = new module.Decoder();
  63441. var geometry;
  63442. var status;
  63443. try {
  63444. var type = decoder.GetEncodedGeometryType(buffer);
  63445. switch (type) {
  63446. case module.TRIANGULAR_MESH:
  63447. geometry = new module.Mesh();
  63448. status = decoder.DecodeBufferToMesh(buffer, geometry);
  63449. break;
  63450. case module.POINT_CLOUD:
  63451. geometry = new module.PointCloud();
  63452. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  63453. break;
  63454. default:
  63455. throw new Error("Invalid geometry type " + type);
  63456. }
  63457. if (!status.ok() || !geometry.ptr) {
  63458. throw new Error(status.error_msg());
  63459. }
  63460. var numPoints = geometry.num_points();
  63461. if (type === module.TRIANGULAR_MESH) {
  63462. var numFaces = geometry.num_faces();
  63463. var faceIndices = new module.DracoInt32Array();
  63464. try {
  63465. var indices = new Uint32Array(numFaces * 3);
  63466. for (var i = 0; i < numFaces; i++) {
  63467. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  63468. var offset = i * 3;
  63469. indices[offset + 0] = faceIndices.GetValue(0);
  63470. indices[offset + 1] = faceIndices.GetValue(1);
  63471. indices[offset + 2] = faceIndices.GetValue(2);
  63472. }
  63473. vertexData.indices = indices;
  63474. }
  63475. finally {
  63476. module.destroy(faceIndices);
  63477. }
  63478. }
  63479. for (var kind in attributes) {
  63480. var uniqueId = attributes[kind];
  63481. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  63482. var dracoData = new module.DracoFloat32Array();
  63483. try {
  63484. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  63485. var babylonData = new Float32Array(numPoints * attribute.num_components());
  63486. for (var i = 0; i < babylonData.length; i++) {
  63487. babylonData[i] = dracoData.GetValue(i);
  63488. }
  63489. vertexData.set(babylonData, kind);
  63490. }
  63491. finally {
  63492. module.destroy(dracoData);
  63493. }
  63494. }
  63495. }
  63496. finally {
  63497. if (geometry) {
  63498. module.destroy(geometry);
  63499. }
  63500. module.destroy(decoder);
  63501. module.destroy(buffer);
  63502. }
  63503. return vertexData;
  63504. });
  63505. };
  63506. DracoCompression._GetDecoderModule = function () {
  63507. if (!DracoCompression._DecoderModulePromise) {
  63508. var promise = null;
  63509. var config_1 = {};
  63510. if (typeof DracoDecoderModule !== "undefined") {
  63511. promise = Promise.resolve();
  63512. }
  63513. else {
  63514. var decoder = DracoCompression.Configuration.decoder;
  63515. if (decoder) {
  63516. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63517. promise = Promise.all([
  63518. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  63519. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  63520. config_1.wasmBinary = data;
  63521. })
  63522. ]);
  63523. }
  63524. else if (decoder.fallbackUrl) {
  63525. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  63526. }
  63527. }
  63528. }
  63529. if (!promise) {
  63530. throw new Error("Draco decoder module is not available");
  63531. }
  63532. DracoCompression._DecoderModulePromise = promise.then(function () {
  63533. return new Promise(function (resolve) {
  63534. config_1.onModuleLoaded = function (decoderModule) {
  63535. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  63536. resolve({ module: decoderModule });
  63537. };
  63538. DracoDecoderModule(config_1);
  63539. });
  63540. });
  63541. }
  63542. return DracoCompression._DecoderModulePromise;
  63543. };
  63544. DracoCompression._LoadScriptAsync = function (url) {
  63545. return new Promise(function (resolve, reject) {
  63546. BABYLON.Tools.LoadScript(url, function () {
  63547. resolve();
  63548. }, function (message) {
  63549. reject(new Error(message));
  63550. });
  63551. });
  63552. };
  63553. DracoCompression._LoadFileAsync = function (url) {
  63554. return new Promise(function (resolve, reject) {
  63555. BABYLON.Tools.LoadFile(url, function (data) {
  63556. resolve(data);
  63557. }, undefined, undefined, true, function (request, exception) {
  63558. reject(exception);
  63559. });
  63560. });
  63561. };
  63562. /**
  63563. * The configuration. Defaults to the following urls:
  63564. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  63565. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  63566. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63567. */
  63568. DracoCompression.Configuration = {
  63569. decoder: {
  63570. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  63571. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  63572. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63573. }
  63574. };
  63575. return DracoCompression;
  63576. }());
  63577. BABYLON.DracoCompression = DracoCompression;
  63578. })(BABYLON || (BABYLON = {}));
  63579. //# sourceMappingURL=babylon.dracoCompression.js.map
  63580. var BABYLON;
  63581. (function (BABYLON) {
  63582. var AudioEngine = /** @class */ (function () {
  63583. function AudioEngine() {
  63584. this._audioContext = null;
  63585. this._audioContextInitialized = false;
  63586. this.canUseWebAudio = false;
  63587. this.WarnedWebAudioUnsupported = false;
  63588. this.unlocked = false;
  63589. this.isMP3supported = false;
  63590. this.isOGGsupported = false;
  63591. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  63592. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  63593. this.canUseWebAudio = true;
  63594. }
  63595. var audioElem = document.createElement('audio');
  63596. try {
  63597. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  63598. this.isMP3supported = true;
  63599. }
  63600. }
  63601. catch (e) {
  63602. // protect error during capability check.
  63603. }
  63604. try {
  63605. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  63606. this.isOGGsupported = true;
  63607. }
  63608. }
  63609. catch (e) {
  63610. // protect error during capability check.
  63611. }
  63612. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  63613. this._unlockiOSaudio();
  63614. }
  63615. else {
  63616. this.unlocked = true;
  63617. }
  63618. }
  63619. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  63620. get: function () {
  63621. if (!this._audioContextInitialized) {
  63622. this._initializeAudioContext();
  63623. }
  63624. return this._audioContext;
  63625. },
  63626. enumerable: true,
  63627. configurable: true
  63628. });
  63629. AudioEngine.prototype._unlockiOSaudio = function () {
  63630. var _this = this;
  63631. var unlockaudio = function () {
  63632. if (!_this.audioContext) {
  63633. return;
  63634. }
  63635. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  63636. var source = _this.audioContext.createBufferSource();
  63637. source.buffer = buffer;
  63638. source.connect(_this.audioContext.destination);
  63639. source.start(0);
  63640. setTimeout(function () {
  63641. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  63642. _this.unlocked = true;
  63643. window.removeEventListener('touchend', unlockaudio, false);
  63644. if (_this.onAudioUnlocked) {
  63645. _this.onAudioUnlocked();
  63646. }
  63647. }
  63648. }, 0);
  63649. };
  63650. window.addEventListener('touchend', unlockaudio, false);
  63651. };
  63652. AudioEngine.prototype._initializeAudioContext = function () {
  63653. try {
  63654. if (this.canUseWebAudio) {
  63655. this._audioContext = new AudioContext();
  63656. // create a global volume gain node
  63657. this.masterGain = this._audioContext.createGain();
  63658. this.masterGain.gain.value = 1;
  63659. this.masterGain.connect(this._audioContext.destination);
  63660. this._audioContextInitialized = true;
  63661. }
  63662. }
  63663. catch (e) {
  63664. this.canUseWebAudio = false;
  63665. BABYLON.Tools.Error("Web Audio: " + e.message);
  63666. }
  63667. };
  63668. AudioEngine.prototype.dispose = function () {
  63669. if (this.canUseWebAudio && this._audioContextInitialized) {
  63670. if (this._connectedAnalyser && this._audioContext) {
  63671. this._connectedAnalyser.stopDebugCanvas();
  63672. this._connectedAnalyser.dispose();
  63673. this.masterGain.disconnect();
  63674. this.masterGain.connect(this._audioContext.destination);
  63675. this._connectedAnalyser = null;
  63676. }
  63677. this.masterGain.gain.value = 1;
  63678. }
  63679. this.WarnedWebAudioUnsupported = false;
  63680. };
  63681. AudioEngine.prototype.getGlobalVolume = function () {
  63682. if (this.canUseWebAudio && this._audioContextInitialized) {
  63683. return this.masterGain.gain.value;
  63684. }
  63685. else {
  63686. return -1;
  63687. }
  63688. };
  63689. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  63690. if (this.canUseWebAudio && this._audioContextInitialized) {
  63691. this.masterGain.gain.value = newVolume;
  63692. }
  63693. };
  63694. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  63695. if (this._connectedAnalyser) {
  63696. this._connectedAnalyser.stopDebugCanvas();
  63697. }
  63698. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  63699. this._connectedAnalyser = analyser;
  63700. this.masterGain.disconnect();
  63701. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  63702. }
  63703. };
  63704. return AudioEngine;
  63705. }());
  63706. BABYLON.AudioEngine = AudioEngine;
  63707. })(BABYLON || (BABYLON = {}));
  63708. //# sourceMappingURL=babylon.audioEngine.js.map
  63709. var BABYLON;
  63710. (function (BABYLON) {
  63711. var Sound = /** @class */ (function () {
  63712. /**
  63713. * Create a sound and attach it to a scene
  63714. * @param name Name of your sound
  63715. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  63716. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  63717. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  63718. */
  63719. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  63720. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  63721. var _this = this;
  63722. this.autoplay = false;
  63723. this.loop = false;
  63724. this.useCustomAttenuation = false;
  63725. this.spatialSound = false;
  63726. this.refDistance = 1;
  63727. this.rolloffFactor = 1;
  63728. this.maxDistance = 100;
  63729. this.distanceModel = "linear";
  63730. this._panningModel = "equalpower";
  63731. this._playbackRate = 1;
  63732. this._streaming = false;
  63733. this._startTime = 0;
  63734. this._startOffset = 0;
  63735. this._position = BABYLON.Vector3.Zero();
  63736. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  63737. this._volume = 1;
  63738. this._isReadyToPlay = false;
  63739. this.isPlaying = false;
  63740. this.isPaused = false;
  63741. this._isDirectional = false;
  63742. // Used if you'd like to create a directional sound.
  63743. // If not set, the sound will be omnidirectional
  63744. this._coneInnerAngle = 360;
  63745. this._coneOuterAngle = 360;
  63746. this._coneOuterGain = 0;
  63747. this._isOutputConnected = false;
  63748. this._urlType = "Unknown";
  63749. this.name = name;
  63750. this._scene = scene;
  63751. this._readyToPlayCallback = readyToPlayCallback;
  63752. // Default custom attenuation function is a linear attenuation
  63753. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  63754. if (currentDistance < maxDistance) {
  63755. return currentVolume * (1 - currentDistance / maxDistance);
  63756. }
  63757. else {
  63758. return 0;
  63759. }
  63760. };
  63761. if (options) {
  63762. this.autoplay = options.autoplay || false;
  63763. this.loop = options.loop || false;
  63764. // if volume === 0, we need another way to check this option
  63765. if (options.volume !== undefined) {
  63766. this._volume = options.volume;
  63767. }
  63768. this.spatialSound = options.spatialSound || false;
  63769. this.maxDistance = options.maxDistance || 100;
  63770. this.useCustomAttenuation = options.useCustomAttenuation || false;
  63771. this.rolloffFactor = options.rolloffFactor || 1;
  63772. this.refDistance = options.refDistance || 1;
  63773. this.distanceModel = options.distanceModel || "linear";
  63774. this._playbackRate = options.playbackRate || 1;
  63775. this._streaming = options.streaming || false;
  63776. }
  63777. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63778. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  63779. this._soundGain.gain.value = this._volume;
  63780. this._inputAudioNode = this._soundGain;
  63781. this._ouputAudioNode = this._soundGain;
  63782. if (this.spatialSound) {
  63783. this._createSpatialParameters();
  63784. }
  63785. this._scene.mainSoundTrack.AddSound(this);
  63786. var validParameter = true;
  63787. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  63788. if (urlOrArrayBuffer) {
  63789. try {
  63790. if (typeof (urlOrArrayBuffer) === "string") {
  63791. this._urlType = "String";
  63792. }
  63793. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  63794. this._urlType = "ArrayBuffer";
  63795. }
  63796. else if (urlOrArrayBuffer instanceof MediaStream) {
  63797. this._urlType = "MediaStream";
  63798. }
  63799. else if (Array.isArray(urlOrArrayBuffer)) {
  63800. this._urlType = "Array";
  63801. }
  63802. var urls = [];
  63803. var codecSupportedFound = false;
  63804. switch (this._urlType) {
  63805. case "MediaStream":
  63806. this._streaming = true;
  63807. this._isReadyToPlay = true;
  63808. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  63809. if (this.autoplay) {
  63810. this.play();
  63811. }
  63812. if (this._readyToPlayCallback) {
  63813. this._readyToPlayCallback();
  63814. }
  63815. break;
  63816. case "ArrayBuffer":
  63817. if (urlOrArrayBuffer.byteLength > 0) {
  63818. codecSupportedFound = true;
  63819. this._soundLoaded(urlOrArrayBuffer);
  63820. }
  63821. break;
  63822. case "String":
  63823. urls.push(urlOrArrayBuffer);
  63824. case "Array":
  63825. if (urls.length === 0)
  63826. urls = urlOrArrayBuffer;
  63827. // If we found a supported format, we load it immediately and stop the loop
  63828. for (var i = 0; i < urls.length; i++) {
  63829. var url = urls[i];
  63830. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  63831. codecSupportedFound = true;
  63832. }
  63833. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  63834. codecSupportedFound = true;
  63835. }
  63836. if (url.indexOf(".wav", url.length - 4) !== -1) {
  63837. codecSupportedFound = true;
  63838. }
  63839. if (url.indexOf("blob:") !== -1) {
  63840. codecSupportedFound = true;
  63841. }
  63842. if (codecSupportedFound) {
  63843. // Loading sound using XHR2
  63844. if (!this._streaming) {
  63845. this._scene._loadFile(url, function (data) {
  63846. _this._soundLoaded(data);
  63847. }, undefined, true, true, function (exception) {
  63848. if (exception) {
  63849. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  63850. }
  63851. BABYLON.Tools.Error("Sound creation aborted.");
  63852. _this._scene.mainSoundTrack.RemoveSound(_this);
  63853. });
  63854. }
  63855. // Streaming sound using HTML5 Audio tag
  63856. else {
  63857. this._htmlAudioElement = new Audio(url);
  63858. this._htmlAudioElement.controls = false;
  63859. this._htmlAudioElement.loop = this.loop;
  63860. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  63861. this._htmlAudioElement.preload = "auto";
  63862. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  63863. _this._isReadyToPlay = true;
  63864. if (_this.autoplay) {
  63865. _this.play();
  63866. }
  63867. if (_this._readyToPlayCallback) {
  63868. _this._readyToPlayCallback();
  63869. }
  63870. });
  63871. document.body.appendChild(this._htmlAudioElement);
  63872. }
  63873. break;
  63874. }
  63875. }
  63876. break;
  63877. default:
  63878. validParameter = false;
  63879. break;
  63880. }
  63881. if (!validParameter) {
  63882. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  63883. }
  63884. else {
  63885. if (!codecSupportedFound) {
  63886. this._isReadyToPlay = true;
  63887. // Simulating a ready to play event to avoid breaking code path
  63888. if (this._readyToPlayCallback) {
  63889. window.setTimeout(function () {
  63890. if (_this._readyToPlayCallback) {
  63891. _this._readyToPlayCallback();
  63892. }
  63893. }, 1000);
  63894. }
  63895. }
  63896. }
  63897. }
  63898. catch (ex) {
  63899. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  63900. this._scene.mainSoundTrack.RemoveSound(this);
  63901. }
  63902. }
  63903. }
  63904. else {
  63905. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  63906. this._scene.mainSoundTrack.AddSound(this);
  63907. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  63908. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  63909. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  63910. }
  63911. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  63912. if (this._readyToPlayCallback) {
  63913. window.setTimeout(function () {
  63914. if (_this._readyToPlayCallback) {
  63915. _this._readyToPlayCallback();
  63916. }
  63917. }, 1000);
  63918. }
  63919. }
  63920. }
  63921. Sound.prototype.dispose = function () {
  63922. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63923. if (this.isPlaying) {
  63924. this.stop();
  63925. }
  63926. this._isReadyToPlay = false;
  63927. if (this.soundTrackId === -1) {
  63928. this._scene.mainSoundTrack.RemoveSound(this);
  63929. }
  63930. else {
  63931. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  63932. }
  63933. if (this._soundGain) {
  63934. this._soundGain.disconnect();
  63935. this._soundGain = null;
  63936. }
  63937. if (this._soundPanner) {
  63938. this._soundPanner.disconnect();
  63939. this._soundPanner = null;
  63940. }
  63941. if (this._soundSource) {
  63942. this._soundSource.disconnect();
  63943. this._soundSource = null;
  63944. }
  63945. this._audioBuffer = null;
  63946. if (this._htmlAudioElement) {
  63947. this._htmlAudioElement.pause();
  63948. this._htmlAudioElement.src = "";
  63949. document.body.removeChild(this._htmlAudioElement);
  63950. }
  63951. if (this._streamingSource) {
  63952. this._streamingSource.disconnect();
  63953. }
  63954. if (this._connectedMesh && this._registerFunc) {
  63955. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63956. this._connectedMesh = null;
  63957. }
  63958. }
  63959. };
  63960. Sound.prototype.isReady = function () {
  63961. return this._isReadyToPlay;
  63962. };
  63963. Sound.prototype._soundLoaded = function (audioData) {
  63964. var _this = this;
  63965. if (!BABYLON.Engine.audioEngine.audioContext) {
  63966. return;
  63967. }
  63968. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  63969. _this._audioBuffer = buffer;
  63970. _this._isReadyToPlay = true;
  63971. if (_this.autoplay) {
  63972. _this.play();
  63973. }
  63974. if (_this._readyToPlayCallback) {
  63975. _this._readyToPlayCallback();
  63976. }
  63977. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  63978. };
  63979. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  63980. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63981. this._audioBuffer = audioBuffer;
  63982. this._isReadyToPlay = true;
  63983. }
  63984. };
  63985. Sound.prototype.updateOptions = function (options) {
  63986. if (options) {
  63987. this.loop = options.loop || this.loop;
  63988. this.maxDistance = options.maxDistance || this.maxDistance;
  63989. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  63990. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  63991. this.refDistance = options.refDistance || this.refDistance;
  63992. this.distanceModel = options.distanceModel || this.distanceModel;
  63993. this._playbackRate = options.playbackRate || this._playbackRate;
  63994. this._updateSpatialParameters();
  63995. if (this.isPlaying) {
  63996. if (this._streaming && this._htmlAudioElement) {
  63997. this._htmlAudioElement.playbackRate = this._playbackRate;
  63998. }
  63999. else {
  64000. if (this._soundSource) {
  64001. this._soundSource.playbackRate.value = this._playbackRate;
  64002. }
  64003. }
  64004. }
  64005. }
  64006. };
  64007. Sound.prototype._createSpatialParameters = function () {
  64008. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64009. if (this._scene.headphone) {
  64010. this._panningModel = "HRTF";
  64011. }
  64012. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  64013. this._updateSpatialParameters();
  64014. this._soundPanner.connect(this._ouputAudioNode);
  64015. this._inputAudioNode = this._soundPanner;
  64016. }
  64017. };
  64018. Sound.prototype._updateSpatialParameters = function () {
  64019. if (this.spatialSound && this._soundPanner) {
  64020. if (this.useCustomAttenuation) {
  64021. // Tricks to disable in a way embedded Web Audio attenuation
  64022. this._soundPanner.distanceModel = "linear";
  64023. this._soundPanner.maxDistance = Number.MAX_VALUE;
  64024. this._soundPanner.refDistance = 1;
  64025. this._soundPanner.rolloffFactor = 1;
  64026. this._soundPanner.panningModel = this._panningModel;
  64027. }
  64028. else {
  64029. this._soundPanner.distanceModel = this.distanceModel;
  64030. this._soundPanner.maxDistance = this.maxDistance;
  64031. this._soundPanner.refDistance = this.refDistance;
  64032. this._soundPanner.rolloffFactor = this.rolloffFactor;
  64033. this._soundPanner.panningModel = this._panningModel;
  64034. }
  64035. }
  64036. };
  64037. Sound.prototype.switchPanningModelToHRTF = function () {
  64038. this._panningModel = "HRTF";
  64039. this._switchPanningModel();
  64040. };
  64041. Sound.prototype.switchPanningModelToEqualPower = function () {
  64042. this._panningModel = "equalpower";
  64043. this._switchPanningModel();
  64044. };
  64045. Sound.prototype._switchPanningModel = function () {
  64046. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64047. this._soundPanner.panningModel = this._panningModel;
  64048. }
  64049. };
  64050. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  64051. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64052. if (this._isOutputConnected) {
  64053. this._ouputAudioNode.disconnect();
  64054. }
  64055. this._ouputAudioNode.connect(soundTrackAudioNode);
  64056. this._isOutputConnected = true;
  64057. }
  64058. };
  64059. /**
  64060. * Transform this sound into a directional source
  64061. * @param coneInnerAngle Size of the inner cone in degree
  64062. * @param coneOuterAngle Size of the outer cone in degree
  64063. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  64064. */
  64065. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  64066. if (coneOuterAngle < coneInnerAngle) {
  64067. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  64068. return;
  64069. }
  64070. this._coneInnerAngle = coneInnerAngle;
  64071. this._coneOuterAngle = coneOuterAngle;
  64072. this._coneOuterGain = coneOuterGain;
  64073. this._isDirectional = true;
  64074. if (this.isPlaying && this.loop) {
  64075. this.stop();
  64076. this.play();
  64077. }
  64078. };
  64079. Sound.prototype.setPosition = function (newPosition) {
  64080. this._position = newPosition;
  64081. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64082. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64083. }
  64084. };
  64085. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  64086. this._localDirection = newLocalDirection;
  64087. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  64088. this._updateDirection();
  64089. }
  64090. };
  64091. Sound.prototype._updateDirection = function () {
  64092. if (!this._connectedMesh || !this._soundPanner) {
  64093. return;
  64094. }
  64095. var mat = this._connectedMesh.getWorldMatrix();
  64096. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  64097. direction.normalize();
  64098. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  64099. };
  64100. Sound.prototype.updateDistanceFromListener = function () {
  64101. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  64102. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  64103. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  64104. }
  64105. };
  64106. Sound.prototype.setAttenuationFunction = function (callback) {
  64107. this._customAttenuationFunction = callback;
  64108. };
  64109. /**
  64110. * Play the sound
  64111. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  64112. * @param offset (optional) Start the sound setting it at a specific time
  64113. */
  64114. Sound.prototype.play = function (time, offset) {
  64115. var _this = this;
  64116. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  64117. try {
  64118. if (this._startOffset < 0) {
  64119. time = -this._startOffset;
  64120. this._startOffset = 0;
  64121. }
  64122. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64123. if (!this._soundSource || !this._streamingSource) {
  64124. if (this.spatialSound && this._soundPanner) {
  64125. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64126. if (this._isDirectional) {
  64127. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64128. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64129. this._soundPanner.coneOuterGain = this._coneOuterGain;
  64130. if (this._connectedMesh) {
  64131. this._updateDirection();
  64132. }
  64133. else {
  64134. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  64135. }
  64136. }
  64137. }
  64138. }
  64139. if (this._streaming) {
  64140. if (!this._streamingSource) {
  64141. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  64142. this._htmlAudioElement.onended = function () { _this._onended(); };
  64143. this._htmlAudioElement.playbackRate = this._playbackRate;
  64144. }
  64145. this._streamingSource.disconnect();
  64146. this._streamingSource.connect(this._inputAudioNode);
  64147. if (this._htmlAudioElement) {
  64148. this._htmlAudioElement.play();
  64149. }
  64150. }
  64151. else {
  64152. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  64153. this._soundSource.buffer = this._audioBuffer;
  64154. this._soundSource.connect(this._inputAudioNode);
  64155. this._soundSource.loop = this.loop;
  64156. this._soundSource.playbackRate.value = this._playbackRate;
  64157. this._soundSource.onended = function () { _this._onended(); };
  64158. if (this._soundSource.buffer) {
  64159. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  64160. }
  64161. }
  64162. this._startTime = startTime;
  64163. this.isPlaying = true;
  64164. this.isPaused = false;
  64165. }
  64166. catch (ex) {
  64167. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  64168. }
  64169. }
  64170. };
  64171. Sound.prototype._onended = function () {
  64172. this.isPlaying = false;
  64173. if (this.onended) {
  64174. this.onended();
  64175. }
  64176. };
  64177. /**
  64178. * Stop the sound
  64179. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  64180. */
  64181. Sound.prototype.stop = function (time) {
  64182. if (this.isPlaying) {
  64183. if (this._streaming) {
  64184. if (this._htmlAudioElement) {
  64185. this._htmlAudioElement.pause();
  64186. // Test needed for Firefox or it will generate an Invalid State Error
  64187. if (this._htmlAudioElement.currentTime > 0) {
  64188. this._htmlAudioElement.currentTime = 0;
  64189. }
  64190. }
  64191. else {
  64192. this._streamingSource.disconnect();
  64193. }
  64194. }
  64195. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  64196. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64197. this._soundSource.stop(stopTime);
  64198. this._soundSource.onended = function () { };
  64199. if (!this.isPaused) {
  64200. this._startOffset = 0;
  64201. }
  64202. }
  64203. this.isPlaying = false;
  64204. }
  64205. };
  64206. Sound.prototype.pause = function () {
  64207. if (this.isPlaying) {
  64208. this.isPaused = true;
  64209. if (this._streaming) {
  64210. if (this._htmlAudioElement) {
  64211. this._htmlAudioElement.pause();
  64212. }
  64213. else {
  64214. this._streamingSource.disconnect();
  64215. }
  64216. }
  64217. else if (BABYLON.Engine.audioEngine.audioContext) {
  64218. this.stop(0);
  64219. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  64220. }
  64221. }
  64222. };
  64223. Sound.prototype.setVolume = function (newVolume, time) {
  64224. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  64225. if (time && BABYLON.Engine.audioEngine.audioContext) {
  64226. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  64227. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  64228. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  64229. }
  64230. else {
  64231. this._soundGain.gain.value = newVolume;
  64232. }
  64233. }
  64234. this._volume = newVolume;
  64235. };
  64236. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  64237. this._playbackRate = newPlaybackRate;
  64238. if (this.isPlaying) {
  64239. if (this._streaming && this._htmlAudioElement) {
  64240. this._htmlAudioElement.playbackRate = this._playbackRate;
  64241. }
  64242. else if (this._soundSource) {
  64243. this._soundSource.playbackRate.value = this._playbackRate;
  64244. }
  64245. }
  64246. };
  64247. Sound.prototype.getVolume = function () {
  64248. return this._volume;
  64249. };
  64250. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  64251. var _this = this;
  64252. if (this._connectedMesh && this._registerFunc) {
  64253. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64254. this._registerFunc = null;
  64255. }
  64256. this._connectedMesh = meshToConnectTo;
  64257. if (!this.spatialSound) {
  64258. this.spatialSound = true;
  64259. this._createSpatialParameters();
  64260. if (this.isPlaying && this.loop) {
  64261. this.stop();
  64262. this.play();
  64263. }
  64264. }
  64265. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  64266. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  64267. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  64268. };
  64269. Sound.prototype.detachFromMesh = function () {
  64270. if (this._connectedMesh && this._registerFunc) {
  64271. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64272. this._registerFunc = null;
  64273. this._connectedMesh = null;
  64274. }
  64275. };
  64276. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  64277. if (!node.getBoundingInfo) {
  64278. return;
  64279. }
  64280. var mesh = node;
  64281. var boundingInfo = mesh.getBoundingInfo();
  64282. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  64283. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  64284. this._updateDirection();
  64285. }
  64286. };
  64287. Sound.prototype.clone = function () {
  64288. var _this = this;
  64289. if (!this._streaming) {
  64290. var setBufferAndRun = function () {
  64291. if (_this._isReadyToPlay) {
  64292. clonedSound._audioBuffer = _this.getAudioBuffer();
  64293. clonedSound._isReadyToPlay = true;
  64294. if (clonedSound.autoplay) {
  64295. clonedSound.play();
  64296. }
  64297. }
  64298. else {
  64299. window.setTimeout(setBufferAndRun, 300);
  64300. }
  64301. };
  64302. var currentOptions = {
  64303. autoplay: this.autoplay, loop: this.loop,
  64304. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  64305. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  64306. refDistance: this.refDistance, distanceModel: this.distanceModel
  64307. };
  64308. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  64309. if (this.useCustomAttenuation) {
  64310. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  64311. }
  64312. clonedSound.setPosition(this._position);
  64313. clonedSound.setPlaybackRate(this._playbackRate);
  64314. setBufferAndRun();
  64315. return clonedSound;
  64316. }
  64317. // Can't clone a streaming sound
  64318. else {
  64319. return null;
  64320. }
  64321. };
  64322. Sound.prototype.getAudioBuffer = function () {
  64323. return this._audioBuffer;
  64324. };
  64325. Sound.prototype.serialize = function () {
  64326. var serializationObject = {
  64327. name: this.name,
  64328. url: this.name,
  64329. autoplay: this.autoplay,
  64330. loop: this.loop,
  64331. volume: this._volume,
  64332. spatialSound: this.spatialSound,
  64333. maxDistance: this.maxDistance,
  64334. rolloffFactor: this.rolloffFactor,
  64335. refDistance: this.refDistance,
  64336. distanceModel: this.distanceModel,
  64337. playbackRate: this._playbackRate,
  64338. panningModel: this._panningModel,
  64339. soundTrackId: this.soundTrackId
  64340. };
  64341. if (this.spatialSound) {
  64342. if (this._connectedMesh)
  64343. serializationObject.connectedMeshId = this._connectedMesh.id;
  64344. serializationObject.position = this._position.asArray();
  64345. serializationObject.refDistance = this.refDistance;
  64346. serializationObject.distanceModel = this.distanceModel;
  64347. serializationObject.isDirectional = this._isDirectional;
  64348. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  64349. serializationObject.coneInnerAngle = this._coneInnerAngle;
  64350. serializationObject.coneOuterAngle = this._coneOuterAngle;
  64351. serializationObject.coneOuterGain = this._coneOuterGain;
  64352. }
  64353. return serializationObject;
  64354. };
  64355. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  64356. var soundName = parsedSound.name;
  64357. var soundUrl;
  64358. if (parsedSound.url) {
  64359. soundUrl = rootUrl + parsedSound.url;
  64360. }
  64361. else {
  64362. soundUrl = rootUrl + soundName;
  64363. }
  64364. var options = {
  64365. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  64366. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  64367. rolloffFactor: parsedSound.rolloffFactor,
  64368. refDistance: parsedSound.refDistance,
  64369. distanceModel: parsedSound.distanceModel,
  64370. playbackRate: parsedSound.playbackRate
  64371. };
  64372. var newSound;
  64373. if (!sourceSound) {
  64374. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  64375. scene._addPendingData(newSound);
  64376. }
  64377. else {
  64378. var setBufferAndRun = function () {
  64379. if (sourceSound._isReadyToPlay) {
  64380. newSound._audioBuffer = sourceSound.getAudioBuffer();
  64381. newSound._isReadyToPlay = true;
  64382. if (newSound.autoplay) {
  64383. newSound.play();
  64384. }
  64385. }
  64386. else {
  64387. window.setTimeout(setBufferAndRun, 300);
  64388. }
  64389. };
  64390. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  64391. setBufferAndRun();
  64392. }
  64393. if (parsedSound.position) {
  64394. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  64395. newSound.setPosition(soundPosition);
  64396. }
  64397. if (parsedSound.isDirectional) {
  64398. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  64399. if (parsedSound.localDirectionToMesh) {
  64400. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  64401. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  64402. }
  64403. }
  64404. if (parsedSound.connectedMeshId) {
  64405. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  64406. if (connectedMesh) {
  64407. newSound.attachToMesh(connectedMesh);
  64408. }
  64409. }
  64410. return newSound;
  64411. };
  64412. return Sound;
  64413. }());
  64414. BABYLON.Sound = Sound;
  64415. })(BABYLON || (BABYLON = {}));
  64416. //# sourceMappingURL=babylon.sound.js.map
  64417. var BABYLON;
  64418. (function (BABYLON) {
  64419. var SoundTrack = /** @class */ (function () {
  64420. function SoundTrack(scene, options) {
  64421. this.id = -1;
  64422. this._isMainTrack = false;
  64423. this._isInitialized = false;
  64424. this._scene = scene;
  64425. this.soundCollection = new Array();
  64426. this._options = options;
  64427. if (!this._isMainTrack) {
  64428. this._scene.soundTracks.push(this);
  64429. this.id = this._scene.soundTracks.length - 1;
  64430. }
  64431. }
  64432. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  64433. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64434. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  64435. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  64436. if (this._options) {
  64437. if (this._options.volume) {
  64438. this._outputAudioNode.gain.value = this._options.volume;
  64439. }
  64440. if (this._options.mainTrack) {
  64441. this._isMainTrack = this._options.mainTrack;
  64442. }
  64443. }
  64444. this._isInitialized = true;
  64445. }
  64446. };
  64447. SoundTrack.prototype.dispose = function () {
  64448. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  64449. if (this._connectedAnalyser) {
  64450. this._connectedAnalyser.stopDebugCanvas();
  64451. }
  64452. while (this.soundCollection.length) {
  64453. this.soundCollection[0].dispose();
  64454. }
  64455. if (this._outputAudioNode) {
  64456. this._outputAudioNode.disconnect();
  64457. }
  64458. this._outputAudioNode = null;
  64459. }
  64460. };
  64461. SoundTrack.prototype.AddSound = function (sound) {
  64462. if (!this._isInitialized) {
  64463. this._initializeSoundTrackAudioGraph();
  64464. }
  64465. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64466. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  64467. }
  64468. if (sound.soundTrackId) {
  64469. if (sound.soundTrackId === -1) {
  64470. this._scene.mainSoundTrack.RemoveSound(sound);
  64471. }
  64472. else {
  64473. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  64474. }
  64475. }
  64476. this.soundCollection.push(sound);
  64477. sound.soundTrackId = this.id;
  64478. };
  64479. SoundTrack.prototype.RemoveSound = function (sound) {
  64480. var index = this.soundCollection.indexOf(sound);
  64481. if (index !== -1) {
  64482. this.soundCollection.splice(index, 1);
  64483. }
  64484. };
  64485. SoundTrack.prototype.setVolume = function (newVolume) {
  64486. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64487. this._outputAudioNode.gain.value = newVolume;
  64488. }
  64489. };
  64490. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  64491. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64492. for (var i = 0; i < this.soundCollection.length; i++) {
  64493. this.soundCollection[i].switchPanningModelToHRTF();
  64494. }
  64495. }
  64496. };
  64497. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  64498. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64499. for (var i = 0; i < this.soundCollection.length; i++) {
  64500. this.soundCollection[i].switchPanningModelToEqualPower();
  64501. }
  64502. }
  64503. };
  64504. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  64505. if (this._connectedAnalyser) {
  64506. this._connectedAnalyser.stopDebugCanvas();
  64507. }
  64508. this._connectedAnalyser = analyser;
  64509. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64510. this._outputAudioNode.disconnect();
  64511. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  64512. }
  64513. };
  64514. return SoundTrack;
  64515. }());
  64516. BABYLON.SoundTrack = SoundTrack;
  64517. })(BABYLON || (BABYLON = {}));
  64518. //# sourceMappingURL=babylon.soundtrack.js.map
  64519. var BABYLON;
  64520. (function (BABYLON) {
  64521. /**
  64522. * Class used to work with sound analyzer using fast fourier transform (FFT)
  64523. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  64524. */
  64525. var Analyser = /** @class */ (function () {
  64526. /**
  64527. * Creates a new analyser
  64528. * @param scene defines hosting scene
  64529. */
  64530. function Analyser(scene) {
  64531. /**
  64532. * Gets or sets the smoothing
  64533. * @ignorenaming
  64534. */
  64535. this.SMOOTHING = 0.75;
  64536. /**
  64537. * Gets or sets the FFT table size
  64538. * @ignorenaming
  64539. */
  64540. this.FFT_SIZE = 512;
  64541. /**
  64542. * Gets or sets the bar graph amplitude
  64543. * @ignorenaming
  64544. */
  64545. this.BARGRAPHAMPLITUDE = 256;
  64546. /**
  64547. * Gets or sets the position of the debug canvas
  64548. * @ignorenaming
  64549. */
  64550. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  64551. /**
  64552. * Gets or sets the debug canvas size
  64553. * @ignorenaming
  64554. */
  64555. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  64556. this._scene = scene;
  64557. this._audioEngine = BABYLON.Engine.audioEngine;
  64558. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  64559. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  64560. this._webAudioAnalyser.minDecibels = -140;
  64561. this._webAudioAnalyser.maxDecibels = 0;
  64562. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64563. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64564. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  64565. }
  64566. }
  64567. /**
  64568. * Get the number of data values you will have to play with for the visualization
  64569. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  64570. * @returns a number
  64571. */
  64572. Analyser.prototype.getFrequencyBinCount = function () {
  64573. if (this._audioEngine.canUseWebAudio) {
  64574. return this._webAudioAnalyser.frequencyBinCount;
  64575. }
  64576. else {
  64577. return 0;
  64578. }
  64579. };
  64580. /**
  64581. * Gets the current frequency data as a byte array
  64582. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64583. * @returns a Uint8Array
  64584. */
  64585. Analyser.prototype.getByteFrequencyData = function () {
  64586. if (this._audioEngine.canUseWebAudio) {
  64587. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64588. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64589. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  64590. }
  64591. return this._byteFreqs;
  64592. };
  64593. /**
  64594. * Gets the current waveform as a byte array
  64595. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  64596. * @returns a Uint8Array
  64597. */
  64598. Analyser.prototype.getByteTimeDomainData = function () {
  64599. if (this._audioEngine.canUseWebAudio) {
  64600. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64601. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64602. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  64603. }
  64604. return this._byteTime;
  64605. };
  64606. /**
  64607. * Gets the current frequency data as a float array
  64608. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64609. * @returns a Float32Array
  64610. */
  64611. Analyser.prototype.getFloatFrequencyData = function () {
  64612. if (this._audioEngine.canUseWebAudio) {
  64613. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64614. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64615. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  64616. }
  64617. return this._floatFreqs;
  64618. };
  64619. /**
  64620. * Renders the debug canvas
  64621. */
  64622. Analyser.prototype.drawDebugCanvas = function () {
  64623. var _this = this;
  64624. if (this._audioEngine.canUseWebAudio) {
  64625. if (!this._debugCanvas) {
  64626. this._debugCanvas = document.createElement("canvas");
  64627. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  64628. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  64629. this._debugCanvas.style.position = "absolute";
  64630. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  64631. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  64632. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  64633. document.body.appendChild(this._debugCanvas);
  64634. this._registerFunc = function () {
  64635. _this.drawDebugCanvas();
  64636. };
  64637. this._scene.registerBeforeRender(this._registerFunc);
  64638. }
  64639. if (this._registerFunc && this._debugCanvasContext) {
  64640. var workingArray = this.getByteFrequencyData();
  64641. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  64642. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  64643. // Draw the frequency domain chart.
  64644. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  64645. var value = workingArray[i];
  64646. var percent = value / this.BARGRAPHAMPLITUDE;
  64647. var height = this.DEBUGCANVASSIZE.height * percent;
  64648. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  64649. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  64650. var hue = i / this.getFrequencyBinCount() * 360;
  64651. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  64652. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  64653. }
  64654. }
  64655. }
  64656. };
  64657. /**
  64658. * Stops rendering the debug canvas and removes it
  64659. */
  64660. Analyser.prototype.stopDebugCanvas = function () {
  64661. if (this._debugCanvas) {
  64662. if (this._registerFunc) {
  64663. this._scene.unregisterBeforeRender(this._registerFunc);
  64664. this._registerFunc = null;
  64665. }
  64666. document.body.removeChild(this._debugCanvas);
  64667. this._debugCanvas = null;
  64668. this._debugCanvasContext = null;
  64669. }
  64670. };
  64671. /**
  64672. * Connects two audio nodes
  64673. * @param inputAudioNode defines first node to connect
  64674. * @param outputAudioNode defines second node to connect
  64675. */
  64676. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  64677. if (this._audioEngine.canUseWebAudio) {
  64678. inputAudioNode.connect(this._webAudioAnalyser);
  64679. this._webAudioAnalyser.connect(outputAudioNode);
  64680. }
  64681. };
  64682. /**
  64683. * Releases all associated resources
  64684. */
  64685. Analyser.prototype.dispose = function () {
  64686. if (this._audioEngine.canUseWebAudio) {
  64687. this._webAudioAnalyser.disconnect();
  64688. }
  64689. };
  64690. return Analyser;
  64691. }());
  64692. BABYLON.Analyser = Analyser;
  64693. })(BABYLON || (BABYLON = {}));
  64694. //# sourceMappingURL=babylon.analyser.js.map
  64695. var BABYLON;
  64696. (function (BABYLON) {
  64697. var CubeTexture = /** @class */ (function (_super) {
  64698. __extends(CubeTexture, _super);
  64699. /**
  64700. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  64701. * as prefiltered data.
  64702. * @param rootUrl defines the url of the texture or the root name of the six images
  64703. * @param scene defines the scene the texture is attached to
  64704. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  64705. * @param noMipmap defines if mipmaps should be created or not
  64706. * @param files defines the six files to load for the different faces
  64707. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  64708. * @param onError defines a callback triggered in case of error during load
  64709. * @param format defines the internal format to use for the texture once loaded
  64710. * @param prefiltered defines whether or not the texture is created from prefiltered data
  64711. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  64712. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64713. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64714. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64715. * @return the cube texture
  64716. */
  64717. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  64718. if (extensions === void 0) { extensions = null; }
  64719. if (noMipmap === void 0) { noMipmap = false; }
  64720. if (files === void 0) { files = null; }
  64721. if (onLoad === void 0) { onLoad = null; }
  64722. if (onError === void 0) { onError = null; }
  64723. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64724. if (prefiltered === void 0) { prefiltered = false; }
  64725. if (forcedExtension === void 0) { forcedExtension = null; }
  64726. if (createPolynomials === void 0) { createPolynomials = false; }
  64727. if (lodScale === void 0) { lodScale = 0.8; }
  64728. if (lodOffset === void 0) { lodOffset = 0; }
  64729. var _this = _super.call(this, scene) || this;
  64730. /**
  64731. * Gets or sets the center of the bounding box associated with the cube texture
  64732. * It must define where the camera used to render the texture was set
  64733. */
  64734. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64735. _this._rotationY = 0;
  64736. /** @hidden */
  64737. _this._prefiltered = false;
  64738. _this.name = rootUrl;
  64739. _this.url = rootUrl;
  64740. _this._noMipmap = noMipmap;
  64741. _this.hasAlpha = false;
  64742. _this._format = format;
  64743. _this.isCube = true;
  64744. _this._textureMatrix = BABYLON.Matrix.Identity();
  64745. _this._createPolynomials = createPolynomials;
  64746. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64747. if (!rootUrl && !files) {
  64748. return _this;
  64749. }
  64750. var lastDot = rootUrl.lastIndexOf(".");
  64751. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  64752. var isDDS = (extension === ".dds");
  64753. var isEnv = (extension === ".env");
  64754. if (isEnv) {
  64755. _this.gammaSpace = false;
  64756. _this._prefiltered = false;
  64757. }
  64758. else {
  64759. _this._prefiltered = prefiltered;
  64760. if (prefiltered) {
  64761. _this.gammaSpace = false;
  64762. }
  64763. }
  64764. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  64765. if (!files) {
  64766. if (!isEnv && !isDDS && !extensions) {
  64767. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  64768. }
  64769. files = [];
  64770. if (extensions) {
  64771. for (var index = 0; index < extensions.length; index++) {
  64772. files.push(rootUrl + extensions[index]);
  64773. }
  64774. }
  64775. }
  64776. _this._files = files;
  64777. if (!_this._texture) {
  64778. if (!scene.useDelayedTextureLoading) {
  64779. if (prefiltered) {
  64780. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  64781. }
  64782. else {
  64783. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  64784. }
  64785. }
  64786. else {
  64787. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64788. }
  64789. }
  64790. else if (onLoad) {
  64791. if (_this._texture.isReady) {
  64792. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  64793. }
  64794. else {
  64795. _this._texture.onLoadedObservable.add(onLoad);
  64796. }
  64797. }
  64798. return _this;
  64799. }
  64800. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  64801. get: function () {
  64802. return this._boundingBoxSize;
  64803. },
  64804. /**
  64805. * Gets or sets the size of the bounding box associated with the cube texture
  64806. * When defined, the cubemap will switch to local mode
  64807. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64808. * @example https://www.babylonjs-playground.com/#RNASML
  64809. */
  64810. set: function (value) {
  64811. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64812. return;
  64813. }
  64814. this._boundingBoxSize = value;
  64815. var scene = this.getScene();
  64816. if (scene) {
  64817. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64818. }
  64819. },
  64820. enumerable: true,
  64821. configurable: true
  64822. });
  64823. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  64824. /**
  64825. * Gets texture matrix rotation angle around Y axis radians.
  64826. */
  64827. get: function () {
  64828. return this._rotationY;
  64829. },
  64830. /**
  64831. * Sets texture matrix rotation angle around Y axis in radians.
  64832. */
  64833. set: function (value) {
  64834. this._rotationY = value;
  64835. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  64836. },
  64837. enumerable: true,
  64838. configurable: true
  64839. });
  64840. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  64841. var rootUrlKey = "";
  64842. files.forEach(function (url) { return rootUrlKey += url; });
  64843. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  64844. };
  64845. /**
  64846. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  64847. * @param url defines the url of the prefiltered texture
  64848. * @param scene defines the scene the texture is attached to
  64849. * @param forcedExtension defines the extension of the file if different from the url
  64850. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64851. * @return the prefiltered texture
  64852. */
  64853. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  64854. if (forcedExtension === void 0) { forcedExtension = null; }
  64855. if (createPolynomials === void 0) { createPolynomials = true; }
  64856. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  64857. };
  64858. // Methods
  64859. CubeTexture.prototype.delayLoad = function () {
  64860. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64861. return;
  64862. }
  64863. var scene = this.getScene();
  64864. if (!scene) {
  64865. return;
  64866. }
  64867. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64868. this._texture = this._getFromCache(this.url, this._noMipmap);
  64869. if (!this._texture) {
  64870. if (this._prefiltered) {
  64871. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  64872. }
  64873. else {
  64874. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  64875. }
  64876. }
  64877. };
  64878. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  64879. return this._textureMatrix;
  64880. };
  64881. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64882. this._textureMatrix = value;
  64883. };
  64884. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64885. var texture = BABYLON.SerializationHelper.Parse(function () {
  64886. var prefiltered = false;
  64887. if (parsedTexture.prefiltered) {
  64888. prefiltered = parsedTexture.prefiltered;
  64889. }
  64890. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  64891. }, parsedTexture, scene);
  64892. // Local Cubemaps
  64893. if (parsedTexture.boundingBoxPosition) {
  64894. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  64895. }
  64896. if (parsedTexture.boundingBoxSize) {
  64897. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  64898. }
  64899. // Animations
  64900. if (parsedTexture.animations) {
  64901. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  64902. var parsedAnimation = parsedTexture.animations[animationIndex];
  64903. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  64904. }
  64905. }
  64906. return texture;
  64907. };
  64908. CubeTexture.prototype.clone = function () {
  64909. var _this = this;
  64910. return BABYLON.SerializationHelper.Clone(function () {
  64911. var scene = _this.getScene();
  64912. if (!scene) {
  64913. return _this;
  64914. }
  64915. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  64916. }, this);
  64917. };
  64918. __decorate([
  64919. BABYLON.serialize("rotationY")
  64920. ], CubeTexture.prototype, "_rotationY", void 0);
  64921. return CubeTexture;
  64922. }(BABYLON.BaseTexture));
  64923. BABYLON.CubeTexture = CubeTexture;
  64924. })(BABYLON || (BABYLON = {}));
  64925. //# sourceMappingURL=babylon.cubeTexture.js.map
  64926. var BABYLON;
  64927. (function (BABYLON) {
  64928. /**
  64929. * Raw cube texture where the raw buffers are passed in
  64930. */
  64931. var RawCubeTexture = /** @class */ (function (_super) {
  64932. __extends(RawCubeTexture, _super);
  64933. /**
  64934. * Creates a cube texture where the raw buffers are passed in.
  64935. * @param scene defines the scene the texture is attached to
  64936. * @param data defines the array of data to use to create each face
  64937. * @param size defines the size of the textures
  64938. * @param format defines the format of the data
  64939. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  64940. * @param generateMipMaps defines if the engine should generate the mip levels
  64941. * @param invertY defines if data must be stored with Y axis inverted
  64942. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  64943. * @param compression defines the compression used (null by default)
  64944. */
  64945. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  64946. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64947. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64948. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64949. if (invertY === void 0) { invertY = false; }
  64950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64951. if (compression === void 0) { compression = null; }
  64952. var _this = _super.call(this, "", scene) || this;
  64953. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  64954. return _this;
  64955. }
  64956. /**
  64957. * Updates the raw cube texture.
  64958. * @param data defines the data to store
  64959. * @param format defines the data format
  64960. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  64961. * @param invertY defines if data must be stored with Y axis inverted
  64962. * @param compression defines the compression used (null by default)
  64963. * @param level defines which level of the texture to update
  64964. */
  64965. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  64966. if (compression === void 0) { compression = null; }
  64967. if (level === void 0) { level = 0; }
  64968. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  64969. };
  64970. /**
  64971. * Updates a raw cube texture with RGBD encoded data.
  64972. * @param data defines the array of data [mipmap][face] to use to create each face
  64973. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  64974. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64975. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64976. * @returns a promsie that resolves when the operation is complete
  64977. */
  64978. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  64979. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  64980. if (lodScale === void 0) { lodScale = 0.8; }
  64981. if (lodOffset === void 0) { lodOffset = 0; }
  64982. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  64983. };
  64984. /**
  64985. * Clones the raw cube texture.
  64986. * @return a new cube texture
  64987. */
  64988. RawCubeTexture.prototype.clone = function () {
  64989. var _this = this;
  64990. return BABYLON.SerializationHelper.Clone(function () {
  64991. var scene = _this.getScene();
  64992. var internalTexture = _this._texture;
  64993. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  64994. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  64995. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  64996. }
  64997. return texture;
  64998. }, this);
  64999. };
  65000. /** @hidden */
  65001. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  65002. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  65003. internalTexture._bufferViewArrayArray = data;
  65004. internalTexture._lodGenerationScale = lodScale;
  65005. internalTexture._lodGenerationOffset = lodOffset;
  65006. internalTexture._sphericalPolynomial = sphericalPolynomial;
  65007. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  65008. internalTexture.isReady = true;
  65009. });
  65010. };
  65011. return RawCubeTexture;
  65012. }(BABYLON.CubeTexture));
  65013. BABYLON.RawCubeTexture = RawCubeTexture;
  65014. })(BABYLON || (BABYLON = {}));
  65015. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  65016. var BABYLON;
  65017. (function (BABYLON) {
  65018. var RenderTargetTexture = /** @class */ (function (_super) {
  65019. __extends(RenderTargetTexture, _super);
  65020. /**
  65021. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  65022. * or used a shadow, depth texture...
  65023. * @param name The friendly name of the texture
  65024. * @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)
  65025. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  65026. * @param generateMipMaps True if mip maps need to be generated after render.
  65027. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  65028. * @param type The type of the buffer in the RTT (int, half float, float...)
  65029. * @param isCube True if a cube texture needs to be created
  65030. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  65031. * @param generateDepthBuffer True to generate a depth buffer
  65032. * @param generateStencilBuffer True to generate a stencil buffer
  65033. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  65034. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  65035. */
  65036. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  65037. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  65038. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65039. if (isCube === void 0) { isCube = false; }
  65040. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65041. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65042. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  65043. if (isMulti === void 0) { isMulti = false; }
  65044. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65045. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65046. _this.isCube = isCube;
  65047. _this.renderParticles = true;
  65048. _this.renderSprites = false;
  65049. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  65050. _this.ignoreCameraViewport = false;
  65051. // Events
  65052. /**
  65053. * An event triggered when the texture is unbind.
  65054. */
  65055. _this.onBeforeBindObservable = new BABYLON.Observable();
  65056. /**
  65057. * An event triggered when the texture is unbind.
  65058. */
  65059. _this.onAfterUnbindObservable = new BABYLON.Observable();
  65060. /**
  65061. * An event triggered before rendering the texture
  65062. */
  65063. _this.onBeforeRenderObservable = new BABYLON.Observable();
  65064. /**
  65065. * An event triggered after rendering the texture
  65066. */
  65067. _this.onAfterRenderObservable = new BABYLON.Observable();
  65068. /**
  65069. * An event triggered after the texture clear
  65070. */
  65071. _this.onClearObservable = new BABYLON.Observable();
  65072. _this._currentRefreshId = -1;
  65073. _this._refreshRate = 1;
  65074. _this._samples = 1;
  65075. /**
  65076. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  65077. * It must define where the camera used to render the texture is set
  65078. */
  65079. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65080. scene = _this.getScene();
  65081. if (!scene) {
  65082. return _this;
  65083. }
  65084. _this.renderList = new Array();
  65085. _this._engine = scene.getEngine();
  65086. _this.name = name;
  65087. _this.isRenderTarget = true;
  65088. _this._initialSizeParameter = size;
  65089. _this._processSizeParameter(size);
  65090. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  65091. });
  65092. _this._generateMipMaps = generateMipMaps ? true : false;
  65093. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  65094. // Rendering groups
  65095. _this._renderingManager = new BABYLON.RenderingManager(scene);
  65096. _this._renderingManager._useSceneAutoClearSetup = true;
  65097. if (isMulti) {
  65098. return _this;
  65099. }
  65100. _this._renderTargetOptions = {
  65101. generateMipMaps: generateMipMaps,
  65102. type: type,
  65103. format: format,
  65104. samplingMode: samplingMode,
  65105. generateDepthBuffer: generateDepthBuffer,
  65106. generateStencilBuffer: generateStencilBuffer
  65107. };
  65108. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  65109. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65110. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65111. }
  65112. if (isCube) {
  65113. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  65114. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  65115. _this._textureMatrix = BABYLON.Matrix.Identity();
  65116. }
  65117. else {
  65118. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  65119. }
  65120. return _this;
  65121. }
  65122. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  65123. get: function () {
  65124. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  65125. },
  65126. enumerable: true,
  65127. configurable: true
  65128. });
  65129. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  65130. get: function () {
  65131. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  65132. },
  65133. enumerable: true,
  65134. configurable: true
  65135. });
  65136. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  65137. get: function () {
  65138. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  65139. },
  65140. enumerable: true,
  65141. configurable: true
  65142. });
  65143. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  65144. /**
  65145. * Use this list to define the list of mesh you want to render.
  65146. */
  65147. get: function () {
  65148. return this._renderList;
  65149. },
  65150. set: function (value) {
  65151. this._renderList = value;
  65152. if (this._renderList) {
  65153. this._hookArray(this._renderList);
  65154. }
  65155. },
  65156. enumerable: true,
  65157. configurable: true
  65158. });
  65159. RenderTargetTexture.prototype._hookArray = function (array) {
  65160. var _this = this;
  65161. var oldPush = array.push;
  65162. array.push = function () {
  65163. var items = [];
  65164. for (var _i = 0; _i < arguments.length; _i++) {
  65165. items[_i] = arguments[_i];
  65166. }
  65167. var result = oldPush.apply(array, items);
  65168. _this.getScene().meshes.forEach(function (mesh) {
  65169. mesh._markSubMeshesAsLightDirty();
  65170. });
  65171. return result;
  65172. };
  65173. var oldSplice = array.splice;
  65174. array.splice = function (index, deleteCount) {
  65175. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65176. _this.getScene().meshes.forEach(function (mesh) {
  65177. mesh._markSubMeshesAsLightDirty();
  65178. });
  65179. return deleted;
  65180. };
  65181. };
  65182. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  65183. set: function (callback) {
  65184. if (this._onAfterUnbindObserver) {
  65185. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  65186. }
  65187. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  65188. },
  65189. enumerable: true,
  65190. configurable: true
  65191. });
  65192. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  65193. set: function (callback) {
  65194. if (this._onBeforeRenderObserver) {
  65195. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65196. }
  65197. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65198. },
  65199. enumerable: true,
  65200. configurable: true
  65201. });
  65202. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  65203. set: function (callback) {
  65204. if (this._onAfterRenderObserver) {
  65205. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65206. }
  65207. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65208. },
  65209. enumerable: true,
  65210. configurable: true
  65211. });
  65212. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  65213. set: function (callback) {
  65214. if (this._onClearObserver) {
  65215. this.onClearObservable.remove(this._onClearObserver);
  65216. }
  65217. this._onClearObserver = this.onClearObservable.add(callback);
  65218. },
  65219. enumerable: true,
  65220. configurable: true
  65221. });
  65222. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  65223. get: function () {
  65224. return this._renderTargetOptions;
  65225. },
  65226. enumerable: true,
  65227. configurable: true
  65228. });
  65229. RenderTargetTexture.prototype._onRatioRescale = function () {
  65230. if (this._sizeRatio) {
  65231. this.resize(this._initialSizeParameter);
  65232. }
  65233. };
  65234. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  65235. get: function () {
  65236. return this._boundingBoxSize;
  65237. },
  65238. /**
  65239. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  65240. * When defined, the cubemap will switch to local mode
  65241. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65242. * @example https://www.babylonjs-playground.com/#RNASML
  65243. */
  65244. set: function (value) {
  65245. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65246. return;
  65247. }
  65248. this._boundingBoxSize = value;
  65249. var scene = this.getScene();
  65250. if (scene) {
  65251. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65252. }
  65253. },
  65254. enumerable: true,
  65255. configurable: true
  65256. });
  65257. /**
  65258. * Creates a depth stencil texture.
  65259. * This is only available in WebGL 2 or with the depth texture extension available.
  65260. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  65261. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  65262. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  65263. */
  65264. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  65265. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  65266. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  65267. if (generateStencil === void 0) { generateStencil = false; }
  65268. if (!this.getScene()) {
  65269. return;
  65270. }
  65271. var engine = this.getScene().getEngine();
  65272. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  65273. bilinearFiltering: bilinearFiltering,
  65274. comparisonFunction: comparisonFunction,
  65275. generateStencil: generateStencil,
  65276. isCube: this.isCube
  65277. });
  65278. engine.setFrameBufferDepthStencilTexture(this);
  65279. };
  65280. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  65281. if (size.ratio) {
  65282. this._sizeRatio = size.ratio;
  65283. this._size = {
  65284. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  65285. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  65286. };
  65287. }
  65288. else {
  65289. this._size = size;
  65290. }
  65291. };
  65292. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  65293. get: function () {
  65294. return this._samples;
  65295. },
  65296. set: function (value) {
  65297. if (this._samples === value) {
  65298. return;
  65299. }
  65300. var scene = this.getScene();
  65301. if (!scene) {
  65302. return;
  65303. }
  65304. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  65305. },
  65306. enumerable: true,
  65307. configurable: true
  65308. });
  65309. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  65310. this._currentRefreshId = -1;
  65311. };
  65312. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  65313. get: function () {
  65314. return this._refreshRate;
  65315. },
  65316. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65317. set: function (value) {
  65318. this._refreshRate = value;
  65319. this.resetRefreshCounter();
  65320. },
  65321. enumerable: true,
  65322. configurable: true
  65323. });
  65324. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  65325. if (!this._postProcessManager) {
  65326. var scene = this.getScene();
  65327. if (!scene) {
  65328. return;
  65329. }
  65330. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  65331. this._postProcesses = new Array();
  65332. }
  65333. this._postProcesses.push(postProcess);
  65334. this._postProcesses[0].autoClear = false;
  65335. };
  65336. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  65337. if (!this._postProcesses) {
  65338. return;
  65339. }
  65340. if (dispose) {
  65341. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  65342. var postProcess = _a[_i];
  65343. postProcess.dispose();
  65344. }
  65345. }
  65346. this._postProcesses = [];
  65347. };
  65348. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  65349. if (!this._postProcesses) {
  65350. return;
  65351. }
  65352. var index = this._postProcesses.indexOf(postProcess);
  65353. if (index === -1) {
  65354. return;
  65355. }
  65356. this._postProcesses.splice(index, 1);
  65357. if (this._postProcesses.length > 0) {
  65358. this._postProcesses[0].autoClear = false;
  65359. }
  65360. };
  65361. RenderTargetTexture.prototype._shouldRender = function () {
  65362. if (this._currentRefreshId === -1) { // At least render once
  65363. this._currentRefreshId = 1;
  65364. return true;
  65365. }
  65366. if (this.refreshRate === this._currentRefreshId) {
  65367. this._currentRefreshId = 1;
  65368. return true;
  65369. }
  65370. this._currentRefreshId++;
  65371. return false;
  65372. };
  65373. RenderTargetTexture.prototype.getRenderSize = function () {
  65374. if (this._size.width) {
  65375. return this._size.width;
  65376. }
  65377. return this._size;
  65378. };
  65379. RenderTargetTexture.prototype.getRenderWidth = function () {
  65380. if (this._size.width) {
  65381. return this._size.width;
  65382. }
  65383. return this._size;
  65384. };
  65385. RenderTargetTexture.prototype.getRenderHeight = function () {
  65386. if (this._size.width) {
  65387. return this._size.height;
  65388. }
  65389. return this._size;
  65390. };
  65391. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  65392. get: function () {
  65393. return true;
  65394. },
  65395. enumerable: true,
  65396. configurable: true
  65397. });
  65398. RenderTargetTexture.prototype.scale = function (ratio) {
  65399. var newSize = this.getRenderSize() * ratio;
  65400. this.resize(newSize);
  65401. };
  65402. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  65403. if (this.isCube) {
  65404. return this._textureMatrix;
  65405. }
  65406. return _super.prototype.getReflectionTextureMatrix.call(this);
  65407. };
  65408. RenderTargetTexture.prototype.resize = function (size) {
  65409. this.releaseInternalTexture();
  65410. var scene = this.getScene();
  65411. if (!scene) {
  65412. return;
  65413. }
  65414. this._processSizeParameter(size);
  65415. if (this.isCube) {
  65416. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  65417. }
  65418. else {
  65419. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  65420. }
  65421. };
  65422. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  65423. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  65424. if (dumpForDebug === void 0) { dumpForDebug = false; }
  65425. var scene = this.getScene();
  65426. if (!scene) {
  65427. return;
  65428. }
  65429. var engine = scene.getEngine();
  65430. if (this.useCameraPostProcesses !== undefined) {
  65431. useCameraPostProcess = this.useCameraPostProcesses;
  65432. }
  65433. if (this._waitingRenderList) {
  65434. this.renderList = [];
  65435. for (var index = 0; index < this._waitingRenderList.length; index++) {
  65436. var id = this._waitingRenderList[index];
  65437. var mesh_1 = scene.getMeshByID(id);
  65438. if (mesh_1) {
  65439. this.renderList.push(mesh_1);
  65440. }
  65441. }
  65442. delete this._waitingRenderList;
  65443. }
  65444. // Is predicate defined?
  65445. if (this.renderListPredicate) {
  65446. if (this.renderList) {
  65447. this.renderList.splice(0); // Clear previous renderList
  65448. }
  65449. else {
  65450. this.renderList = [];
  65451. }
  65452. var scene = this.getScene();
  65453. if (!scene) {
  65454. return;
  65455. }
  65456. var sceneMeshes = scene.meshes;
  65457. for (var index = 0; index < sceneMeshes.length; index++) {
  65458. var mesh = sceneMeshes[index];
  65459. if (this.renderListPredicate(mesh)) {
  65460. this.renderList.push(mesh);
  65461. }
  65462. }
  65463. }
  65464. this.onBeforeBindObservable.notifyObservers(this);
  65465. // Set custom projection.
  65466. // Needs to be before binding to prevent changing the aspect ratio.
  65467. var camera;
  65468. if (this.activeCamera) {
  65469. camera = this.activeCamera;
  65470. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65471. if (this.activeCamera !== scene.activeCamera) {
  65472. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  65473. }
  65474. }
  65475. else {
  65476. camera = scene.activeCamera;
  65477. if (camera) {
  65478. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65479. }
  65480. }
  65481. // Prepare renderingManager
  65482. this._renderingManager.reset();
  65483. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  65484. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  65485. var sceneRenderId = scene.getRenderId();
  65486. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  65487. var mesh = currentRenderList[meshIndex];
  65488. if (mesh) {
  65489. if (!mesh.isReady(this.refreshRate === 0)) {
  65490. this.resetRefreshCounter();
  65491. continue;
  65492. }
  65493. mesh._preActivateForIntermediateRendering(sceneRenderId);
  65494. var isMasked = void 0;
  65495. if (!this.renderList && camera) {
  65496. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  65497. }
  65498. else {
  65499. isMasked = false;
  65500. }
  65501. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  65502. mesh._activate(sceneRenderId);
  65503. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  65504. var subMesh = mesh.subMeshes[subIndex];
  65505. scene._activeIndices.addCount(subMesh.indexCount, false);
  65506. this._renderingManager.dispatch(subMesh, mesh);
  65507. }
  65508. }
  65509. }
  65510. }
  65511. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  65512. var particleSystem = scene.particleSystems[particleIndex];
  65513. var emitter = particleSystem.emitter;
  65514. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  65515. continue;
  65516. }
  65517. if (currentRenderList.indexOf(emitter) >= 0) {
  65518. this._renderingManager.dispatchParticles(particleSystem);
  65519. }
  65520. }
  65521. if (this.isCube) {
  65522. for (var face = 0; face < 6; face++) {
  65523. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65524. scene.incrementRenderId();
  65525. scene.resetCachedMaterial();
  65526. }
  65527. }
  65528. else {
  65529. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65530. }
  65531. this.onAfterUnbindObservable.notifyObservers(this);
  65532. if (scene.activeCamera) {
  65533. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  65534. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  65535. }
  65536. engine.setViewport(scene.activeCamera.viewport);
  65537. }
  65538. scene.resetCachedMaterial();
  65539. };
  65540. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  65541. var minimum = 128;
  65542. var x = renderDimension * scale;
  65543. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  65544. // Ensure we don't exceed the render dimension (while staying POT)
  65545. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  65546. };
  65547. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65548. var _this = this;
  65549. if (!this._texture) {
  65550. return;
  65551. }
  65552. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  65553. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65554. });
  65555. };
  65556. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  65557. var scene = this.getScene();
  65558. if (!scene) {
  65559. return;
  65560. }
  65561. var engine = scene.getEngine();
  65562. if (!this._texture) {
  65563. return;
  65564. }
  65565. // Bind
  65566. if (this._postProcessManager) {
  65567. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  65568. }
  65569. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  65570. if (this._texture) {
  65571. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  65572. }
  65573. }
  65574. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  65575. // Clear
  65576. if (this.onClearObservable.hasObservers()) {
  65577. this.onClearObservable.notifyObservers(engine);
  65578. }
  65579. else {
  65580. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  65581. }
  65582. if (!this._doNotChangeAspectRatio) {
  65583. scene.updateTransformMatrix(true);
  65584. }
  65585. // Render
  65586. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  65587. if (this._postProcessManager) {
  65588. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  65589. }
  65590. else if (useCameraPostProcess) {
  65591. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  65592. }
  65593. if (!this._doNotChangeAspectRatio) {
  65594. scene.updateTransformMatrix(true);
  65595. }
  65596. // Dump ?
  65597. if (dumpForDebug) {
  65598. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  65599. }
  65600. // Unbind
  65601. if (!this.isCube || faceIndex === 5) {
  65602. if (this.isCube) {
  65603. if (faceIndex === 5) {
  65604. engine.generateMipMapsForCubemap(this._texture);
  65605. }
  65606. }
  65607. this.unbindFrameBuffer(engine, faceIndex);
  65608. }
  65609. else {
  65610. this.onAfterRenderObservable.notifyObservers(faceIndex);
  65611. }
  65612. };
  65613. /**
  65614. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  65615. * This allowed control for front to back rendering or reversly depending of the special needs.
  65616. *
  65617. * @param renderingGroupId The rendering group id corresponding to its index
  65618. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  65619. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  65620. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  65621. */
  65622. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  65623. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  65624. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  65625. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  65626. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  65627. };
  65628. /**
  65629. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  65630. *
  65631. * @param renderingGroupId The rendering group id corresponding to its index
  65632. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  65633. */
  65634. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  65635. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  65636. this._renderingManager._useSceneAutoClearSetup = false;
  65637. };
  65638. RenderTargetTexture.prototype.clone = function () {
  65639. var textureSize = this.getSize();
  65640. 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);
  65641. // Base texture
  65642. newTexture.hasAlpha = this.hasAlpha;
  65643. newTexture.level = this.level;
  65644. // RenderTarget Texture
  65645. newTexture.coordinatesMode = this.coordinatesMode;
  65646. if (this.renderList) {
  65647. newTexture.renderList = this.renderList.slice(0);
  65648. }
  65649. return newTexture;
  65650. };
  65651. RenderTargetTexture.prototype.serialize = function () {
  65652. if (!this.name) {
  65653. return null;
  65654. }
  65655. var serializationObject = _super.prototype.serialize.call(this);
  65656. serializationObject.renderTargetSize = this.getRenderSize();
  65657. serializationObject.renderList = [];
  65658. if (this.renderList) {
  65659. for (var index = 0; index < this.renderList.length; index++) {
  65660. serializationObject.renderList.push(this.renderList[index].id);
  65661. }
  65662. }
  65663. return serializationObject;
  65664. };
  65665. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  65666. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  65667. var objBuffer = this.getInternalTexture();
  65668. var scene = this.getScene();
  65669. if (objBuffer && scene) {
  65670. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  65671. }
  65672. };
  65673. RenderTargetTexture.prototype.dispose = function () {
  65674. if (this._postProcessManager) {
  65675. this._postProcessManager.dispose();
  65676. this._postProcessManager = null;
  65677. }
  65678. this.clearPostProcesses(true);
  65679. if (this._resizeObserver) {
  65680. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  65681. this._resizeObserver = null;
  65682. }
  65683. this.renderList = null;
  65684. // Remove from custom render targets
  65685. var scene = this.getScene();
  65686. if (!scene) {
  65687. return;
  65688. }
  65689. var index = scene.customRenderTargets.indexOf(this);
  65690. if (index >= 0) {
  65691. scene.customRenderTargets.splice(index, 1);
  65692. }
  65693. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  65694. var camera = _a[_i];
  65695. index = camera.customRenderTargets.indexOf(this);
  65696. if (index >= 0) {
  65697. camera.customRenderTargets.splice(index, 1);
  65698. }
  65699. }
  65700. _super.prototype.dispose.call(this);
  65701. };
  65702. RenderTargetTexture.prototype._rebuild = function () {
  65703. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65704. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65705. }
  65706. if (this._postProcessManager) {
  65707. this._postProcessManager._rebuild();
  65708. }
  65709. };
  65710. /**
  65711. * Clear the info related to rendering groups preventing retention point in material dispose.
  65712. */
  65713. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  65714. if (this._renderingManager) {
  65715. this._renderingManager.freeRenderingGroups();
  65716. }
  65717. };
  65718. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  65719. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  65720. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  65721. return RenderTargetTexture;
  65722. }(BABYLON.Texture));
  65723. BABYLON.RenderTargetTexture = RenderTargetTexture;
  65724. })(BABYLON || (BABYLON = {}));
  65725. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  65726. var BABYLON;
  65727. (function (BABYLON) {
  65728. ;
  65729. var MultiRenderTarget = /** @class */ (function (_super) {
  65730. __extends(MultiRenderTarget, _super);
  65731. function MultiRenderTarget(name, size, count, scene, options) {
  65732. var _this = this;
  65733. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  65734. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  65735. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  65736. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  65737. _this._engine = scene.getEngine();
  65738. if (!_this.isSupported) {
  65739. _this.dispose();
  65740. return;
  65741. }
  65742. var types = [];
  65743. var samplingModes = [];
  65744. for (var i = 0; i < count; i++) {
  65745. if (options && options.types && options.types[i] !== undefined) {
  65746. types.push(options.types[i]);
  65747. }
  65748. else {
  65749. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65750. }
  65751. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  65752. samplingModes.push(options.samplingModes[i]);
  65753. }
  65754. else {
  65755. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65756. }
  65757. }
  65758. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  65759. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  65760. _this._size = size;
  65761. _this._multiRenderTargetOptions = {
  65762. samplingModes: samplingModes,
  65763. generateMipMaps: generateMipMaps,
  65764. generateDepthBuffer: generateDepthBuffer,
  65765. generateStencilBuffer: generateStencilBuffer,
  65766. generateDepthTexture: generateDepthTexture,
  65767. types: types,
  65768. textureCount: count
  65769. };
  65770. _this._createInternalTextures();
  65771. _this._createTextures();
  65772. return _this;
  65773. }
  65774. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  65775. get: function () {
  65776. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  65777. },
  65778. enumerable: true,
  65779. configurable: true
  65780. });
  65781. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  65782. get: function () {
  65783. return this._textures;
  65784. },
  65785. enumerable: true,
  65786. configurable: true
  65787. });
  65788. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  65789. get: function () {
  65790. return this._textures[this._textures.length - 1];
  65791. },
  65792. enumerable: true,
  65793. configurable: true
  65794. });
  65795. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  65796. set: function (wrap) {
  65797. if (this._textures) {
  65798. for (var i = 0; i < this._textures.length; i++) {
  65799. this._textures[i].wrapU = wrap;
  65800. }
  65801. }
  65802. },
  65803. enumerable: true,
  65804. configurable: true
  65805. });
  65806. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  65807. set: function (wrap) {
  65808. if (this._textures) {
  65809. for (var i = 0; i < this._textures.length; i++) {
  65810. this._textures[i].wrapV = wrap;
  65811. }
  65812. }
  65813. },
  65814. enumerable: true,
  65815. configurable: true
  65816. });
  65817. MultiRenderTarget.prototype._rebuild = function () {
  65818. this.releaseInternalTextures();
  65819. this._createInternalTextures();
  65820. for (var i = 0; i < this._internalTextures.length; i++) {
  65821. var texture = this._textures[i];
  65822. texture._texture = this._internalTextures[i];
  65823. }
  65824. // Keeps references to frame buffer and stencil/depth buffer
  65825. this._texture = this._internalTextures[0];
  65826. };
  65827. MultiRenderTarget.prototype._createInternalTextures = function () {
  65828. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  65829. };
  65830. MultiRenderTarget.prototype._createTextures = function () {
  65831. this._textures = [];
  65832. for (var i = 0; i < this._internalTextures.length; i++) {
  65833. var texture = new BABYLON.Texture(null, this.getScene());
  65834. texture._texture = this._internalTextures[i];
  65835. this._textures.push(texture);
  65836. }
  65837. // Keeps references to frame buffer and stencil/depth buffer
  65838. this._texture = this._internalTextures[0];
  65839. };
  65840. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  65841. get: function () {
  65842. return this._samples;
  65843. },
  65844. set: function (value) {
  65845. if (this._samples === value) {
  65846. return;
  65847. }
  65848. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  65849. },
  65850. enumerable: true,
  65851. configurable: true
  65852. });
  65853. MultiRenderTarget.prototype.resize = function (size) {
  65854. this.releaseInternalTextures();
  65855. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  65856. this._createInternalTextures();
  65857. };
  65858. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65859. var _this = this;
  65860. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  65861. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65862. });
  65863. };
  65864. MultiRenderTarget.prototype.dispose = function () {
  65865. this.releaseInternalTextures();
  65866. _super.prototype.dispose.call(this);
  65867. };
  65868. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  65869. if (!this._internalTextures) {
  65870. return;
  65871. }
  65872. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  65873. if (this._internalTextures[i] !== undefined) {
  65874. this._internalTextures[i].dispose();
  65875. this._internalTextures.splice(i, 1);
  65876. }
  65877. }
  65878. };
  65879. return MultiRenderTarget;
  65880. }(BABYLON.RenderTargetTexture));
  65881. BABYLON.MultiRenderTarget = MultiRenderTarget;
  65882. })(BABYLON || (BABYLON = {}));
  65883. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  65884. var BABYLON;
  65885. (function (BABYLON) {
  65886. var MirrorTexture = /** @class */ (function (_super) {
  65887. __extends(MirrorTexture, _super);
  65888. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  65889. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65890. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65891. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65892. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  65893. _this.scene = scene;
  65894. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  65895. _this._transformMatrix = BABYLON.Matrix.Zero();
  65896. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  65897. _this._adaptiveBlurKernel = 0;
  65898. _this._blurKernelX = 0;
  65899. _this._blurKernelY = 0;
  65900. _this._blurRatio = 1.0;
  65901. _this.ignoreCameraViewport = true;
  65902. _this._updateGammaSpace();
  65903. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  65904. _this._updateGammaSpace;
  65905. });
  65906. _this.onBeforeRenderObservable.add(function () {
  65907. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  65908. _this._savedViewMatrix = scene.getViewMatrix();
  65909. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  65910. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  65911. scene.clipPlane = _this.mirrorPlane;
  65912. scene.getEngine().cullBackFaces = false;
  65913. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  65914. });
  65915. _this.onAfterRenderObservable.add(function () {
  65916. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  65917. scene.getEngine().cullBackFaces = true;
  65918. scene._mirroredCameraPosition = null;
  65919. delete scene.clipPlane;
  65920. });
  65921. return _this;
  65922. }
  65923. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  65924. get: function () {
  65925. return this._blurRatio;
  65926. },
  65927. set: function (value) {
  65928. if (this._blurRatio === value) {
  65929. return;
  65930. }
  65931. this._blurRatio = value;
  65932. this._preparePostProcesses();
  65933. },
  65934. enumerable: true,
  65935. configurable: true
  65936. });
  65937. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  65938. set: function (value) {
  65939. this._adaptiveBlurKernel = value;
  65940. this._autoComputeBlurKernel();
  65941. },
  65942. enumerable: true,
  65943. configurable: true
  65944. });
  65945. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  65946. set: function (value) {
  65947. this.blurKernelX = value;
  65948. this.blurKernelY = value;
  65949. },
  65950. enumerable: true,
  65951. configurable: true
  65952. });
  65953. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  65954. get: function () {
  65955. return this._blurKernelX;
  65956. },
  65957. set: function (value) {
  65958. if (this._blurKernelX === value) {
  65959. return;
  65960. }
  65961. this._blurKernelX = value;
  65962. this._preparePostProcesses();
  65963. },
  65964. enumerable: true,
  65965. configurable: true
  65966. });
  65967. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  65968. get: function () {
  65969. return this._blurKernelY;
  65970. },
  65971. set: function (value) {
  65972. if (this._blurKernelY === value) {
  65973. return;
  65974. }
  65975. this._blurKernelY = value;
  65976. this._preparePostProcesses();
  65977. },
  65978. enumerable: true,
  65979. configurable: true
  65980. });
  65981. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  65982. var engine = this.getScene().getEngine();
  65983. var dw = this.getRenderWidth() / engine.getRenderWidth();
  65984. var dh = this.getRenderHeight() / engine.getRenderHeight();
  65985. this.blurKernelX = this._adaptiveBlurKernel * dw;
  65986. this.blurKernelY = this._adaptiveBlurKernel * dh;
  65987. };
  65988. MirrorTexture.prototype._onRatioRescale = function () {
  65989. if (this._sizeRatio) {
  65990. this.resize(this._initialSizeParameter);
  65991. if (!this._adaptiveBlurKernel) {
  65992. this._preparePostProcesses();
  65993. }
  65994. }
  65995. if (this._adaptiveBlurKernel) {
  65996. this._autoComputeBlurKernel();
  65997. }
  65998. };
  65999. MirrorTexture.prototype._updateGammaSpace = function () {
  66000. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  66001. };
  66002. MirrorTexture.prototype._preparePostProcesses = function () {
  66003. this.clearPostProcesses(true);
  66004. if (this._blurKernelX && this._blurKernelY) {
  66005. var engine = this.getScene().getEngine();
  66006. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66007. 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);
  66008. this._blurX.autoClear = false;
  66009. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  66010. this._blurX.inputTexture = this._texture;
  66011. }
  66012. else {
  66013. this._blurX.alwaysForcePOT = true;
  66014. }
  66015. 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);
  66016. this._blurY.autoClear = false;
  66017. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  66018. this.addPostProcess(this._blurX);
  66019. this.addPostProcess(this._blurY);
  66020. }
  66021. else {
  66022. if (this._blurY) {
  66023. this.removePostProcess(this._blurY);
  66024. this._blurY.dispose();
  66025. this._blurY = null;
  66026. }
  66027. if (this._blurX) {
  66028. this.removePostProcess(this._blurX);
  66029. this._blurX.dispose();
  66030. this._blurX = null;
  66031. }
  66032. }
  66033. };
  66034. MirrorTexture.prototype.clone = function () {
  66035. var scene = this.getScene();
  66036. if (!scene) {
  66037. return this;
  66038. }
  66039. var textureSize = this.getSize();
  66040. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  66041. // Base texture
  66042. newTexture.hasAlpha = this.hasAlpha;
  66043. newTexture.level = this.level;
  66044. // Mirror Texture
  66045. newTexture.mirrorPlane = this.mirrorPlane.clone();
  66046. if (this.renderList) {
  66047. newTexture.renderList = this.renderList.slice(0);
  66048. }
  66049. return newTexture;
  66050. };
  66051. MirrorTexture.prototype.serialize = function () {
  66052. if (!this.name) {
  66053. return null;
  66054. }
  66055. var serializationObject = _super.prototype.serialize.call(this);
  66056. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  66057. return serializationObject;
  66058. };
  66059. MirrorTexture.prototype.dispose = function () {
  66060. _super.prototype.dispose.call(this);
  66061. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  66062. };
  66063. return MirrorTexture;
  66064. }(BABYLON.RenderTargetTexture));
  66065. BABYLON.MirrorTexture = MirrorTexture;
  66066. })(BABYLON || (BABYLON = {}));
  66067. //# sourceMappingURL=babylon.mirrorTexture.js.map
  66068. var BABYLON;
  66069. (function (BABYLON) {
  66070. /**
  66071. * Creates a refraction texture used by refraction channel of the standard material.
  66072. * @param name the texture name
  66073. * @param size size of the underlying texture
  66074. * @param scene root scene
  66075. */
  66076. var RefractionTexture = /** @class */ (function (_super) {
  66077. __extends(RefractionTexture, _super);
  66078. function RefractionTexture(name, size, scene, generateMipMaps) {
  66079. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  66080. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  66081. _this.depth = 2.0;
  66082. _this.onBeforeRenderObservable.add(function () {
  66083. scene.clipPlane = _this.refractionPlane;
  66084. });
  66085. _this.onAfterRenderObservable.add(function () {
  66086. delete scene.clipPlane;
  66087. });
  66088. return _this;
  66089. }
  66090. RefractionTexture.prototype.clone = function () {
  66091. var scene = this.getScene();
  66092. if (!scene) {
  66093. return this;
  66094. }
  66095. var textureSize = this.getSize();
  66096. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  66097. // Base texture
  66098. newTexture.hasAlpha = this.hasAlpha;
  66099. newTexture.level = this.level;
  66100. // Refraction Texture
  66101. newTexture.refractionPlane = this.refractionPlane.clone();
  66102. if (this.renderList) {
  66103. newTexture.renderList = this.renderList.slice(0);
  66104. }
  66105. newTexture.depth = this.depth;
  66106. return newTexture;
  66107. };
  66108. RefractionTexture.prototype.serialize = function () {
  66109. if (!this.name) {
  66110. return null;
  66111. }
  66112. var serializationObject = _super.prototype.serialize.call(this);
  66113. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  66114. serializationObject.depth = this.depth;
  66115. return serializationObject;
  66116. };
  66117. return RefractionTexture;
  66118. }(BABYLON.RenderTargetTexture));
  66119. BABYLON.RefractionTexture = RefractionTexture;
  66120. })(BABYLON || (BABYLON = {}));
  66121. //# sourceMappingURL=babylon.refractionTexture.js.map
  66122. var BABYLON;
  66123. (function (BABYLON) {
  66124. /**
  66125. * A class extending {BABYLON.Texture} allowing drawing on a texture
  66126. * @see http://doc.babylonjs.com/how_to/dynamictexture
  66127. */
  66128. var DynamicTexture = /** @class */ (function (_super) {
  66129. __extends(DynamicTexture, _super);
  66130. /**
  66131. * Creates a {BABYLON.DynamicTexture}
  66132. * @param name defines the name of the texture
  66133. * @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
  66134. * @param scene defines the scene where you want the texture
  66135. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  66136. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  66137. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  66138. */
  66139. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  66140. if (scene === void 0) { scene = null; }
  66141. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66142. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66143. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  66144. _this.name = name;
  66145. _this._engine = _this.getScene().getEngine();
  66146. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66147. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66148. _this._generateMipMaps = generateMipMaps;
  66149. if (options.getContext) {
  66150. _this._canvas = options;
  66151. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66152. }
  66153. else {
  66154. _this._canvas = document.createElement("canvas");
  66155. if (options.width || options.width === 0) {
  66156. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66157. }
  66158. else {
  66159. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  66160. }
  66161. }
  66162. var textureSize = _this.getSize();
  66163. _this._canvas.width = textureSize.width;
  66164. _this._canvas.height = textureSize.height;
  66165. _this._context = _this._canvas.getContext("2d");
  66166. return _this;
  66167. }
  66168. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  66169. /**
  66170. * Gets the current state of canRescale
  66171. */
  66172. get: function () {
  66173. return true;
  66174. },
  66175. enumerable: true,
  66176. configurable: true
  66177. });
  66178. DynamicTexture.prototype._recreate = function (textureSize) {
  66179. this._canvas.width = textureSize.width;
  66180. this._canvas.height = textureSize.height;
  66181. this.releaseInternalTexture();
  66182. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  66183. };
  66184. /**
  66185. * Scales the texture
  66186. * @param ratio the scale factor to apply to both width and height
  66187. */
  66188. DynamicTexture.prototype.scale = function (ratio) {
  66189. var textureSize = this.getSize();
  66190. textureSize.width *= ratio;
  66191. textureSize.height *= ratio;
  66192. this._recreate(textureSize);
  66193. };
  66194. /**
  66195. * Resizes the texture
  66196. * @param width the new width
  66197. * @param height the new height
  66198. */
  66199. DynamicTexture.prototype.scaleTo = function (width, height) {
  66200. var textureSize = this.getSize();
  66201. textureSize.width = width;
  66202. textureSize.height = height;
  66203. this._recreate(textureSize);
  66204. };
  66205. /**
  66206. * Gets the context of the canvas used by the texture
  66207. * @returns the canvas context of the dynamic texture
  66208. */
  66209. DynamicTexture.prototype.getContext = function () {
  66210. return this._context;
  66211. };
  66212. /**
  66213. * Clears the texture
  66214. */
  66215. DynamicTexture.prototype.clear = function () {
  66216. var size = this.getSize();
  66217. this._context.fillRect(0, 0, size.width, size.height);
  66218. };
  66219. /**
  66220. * Updates the texture
  66221. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66222. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  66223. */
  66224. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  66225. if (premulAlpha === void 0) { premulAlpha = false; }
  66226. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  66227. };
  66228. /**
  66229. * Draws text onto the texture
  66230. * @param text defines the text to be drawn
  66231. * @param x defines the placement of the text from the left
  66232. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  66233. * @param font defines the font to be used with font-style, font-size, font-name
  66234. * @param color defines the color used for the text
  66235. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  66236. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66237. * @param update defines whether texture is immediately update (default is true)
  66238. */
  66239. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  66240. if (update === void 0) { update = true; }
  66241. var size = this.getSize();
  66242. if (clearColor) {
  66243. this._context.fillStyle = clearColor;
  66244. this._context.fillRect(0, 0, size.width, size.height);
  66245. }
  66246. this._context.font = font;
  66247. if (x === null || x === undefined) {
  66248. var textSize = this._context.measureText(text);
  66249. x = (size.width - textSize.width) / 2;
  66250. }
  66251. if (y === null || y === undefined) {
  66252. var fontSize = parseInt((font.replace(/\D/g, '')));
  66253. y = (size.height / 2) + (fontSize / 3.65);
  66254. }
  66255. this._context.fillStyle = color;
  66256. this._context.fillText(text, x, y);
  66257. if (update) {
  66258. this.update(invertY);
  66259. }
  66260. };
  66261. /**
  66262. * Clones the texture
  66263. * @returns the clone of the texture.
  66264. */
  66265. DynamicTexture.prototype.clone = function () {
  66266. var scene = this.getScene();
  66267. if (!scene) {
  66268. return this;
  66269. }
  66270. var textureSize = this.getSize();
  66271. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  66272. // Base texture
  66273. newTexture.hasAlpha = this.hasAlpha;
  66274. newTexture.level = this.level;
  66275. // Dynamic Texture
  66276. newTexture.wrapU = this.wrapU;
  66277. newTexture.wrapV = this.wrapV;
  66278. return newTexture;
  66279. };
  66280. /** @hidden */
  66281. DynamicTexture.prototype._rebuild = function () {
  66282. this.update();
  66283. };
  66284. return DynamicTexture;
  66285. }(BABYLON.Texture));
  66286. BABYLON.DynamicTexture = DynamicTexture;
  66287. })(BABYLON || (BABYLON = {}));
  66288. //# sourceMappingURL=babylon.dynamicTexture.js.map
  66289. var BABYLON;
  66290. (function (BABYLON) {
  66291. var VideoTexture = /** @class */ (function (_super) {
  66292. __extends(VideoTexture, _super);
  66293. /**
  66294. * Creates a video texture.
  66295. * Sample : https://doc.babylonjs.com/how_to/video_texture
  66296. * @param {string | null} name optional name, will detect from video source, if not defined
  66297. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  66298. * @param {BABYLON.Scene} scene is obviously the current scene.
  66299. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  66300. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  66301. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  66302. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  66303. */
  66304. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  66305. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66306. if (invertY === void 0) { invertY = false; }
  66307. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66308. if (settings === void 0) { settings = {
  66309. autoPlay: true,
  66310. loop: true,
  66311. autoUpdateTexture: true,
  66312. }; }
  66313. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66314. _this._onUserActionRequestedObservable = null;
  66315. _this._stillImageCaptured = false;
  66316. _this._poster = false;
  66317. _this._createInternalTexture = function () {
  66318. if (_this._texture != null) {
  66319. if (_this._poster) {
  66320. _this._texture.dispose();
  66321. _this._poster = false;
  66322. }
  66323. else {
  66324. return;
  66325. }
  66326. }
  66327. if (!_this._engine.needPOTTextures ||
  66328. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  66329. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66330. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66331. }
  66332. else {
  66333. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66334. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66335. _this._generateMipMaps = false;
  66336. }
  66337. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  66338. if (!_this.video.autoplay) {
  66339. var oldHandler_1 = _this.video.onplaying;
  66340. var error_1 = false;
  66341. _this.video.onplaying = function () {
  66342. _this.video.onplaying = oldHandler_1;
  66343. _this._texture.isReady = true;
  66344. _this._updateInternalTexture();
  66345. if (!error_1) {
  66346. _this.video.pause();
  66347. }
  66348. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66349. _this.onLoadObservable.notifyObservers(_this);
  66350. }
  66351. };
  66352. var playing = _this.video.play();
  66353. if (playing) {
  66354. playing.then(function () {
  66355. // Everything is good.
  66356. })
  66357. .catch(function () {
  66358. error_1 = true;
  66359. // On Chrome for instance, new policies might prevent playing without user interaction.
  66360. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  66361. _this._onUserActionRequestedObservable.notifyObservers(_this);
  66362. }
  66363. });
  66364. }
  66365. else {
  66366. _this.video.onplaying = oldHandler_1;
  66367. _this._texture.isReady = true;
  66368. _this._updateInternalTexture();
  66369. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66370. _this.onLoadObservable.notifyObservers(_this);
  66371. }
  66372. }
  66373. }
  66374. else {
  66375. _this._texture.isReady = true;
  66376. _this._updateInternalTexture();
  66377. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66378. _this.onLoadObservable.notifyObservers(_this);
  66379. }
  66380. }
  66381. };
  66382. _this.reset = function () {
  66383. if (_this._texture == null) {
  66384. return;
  66385. }
  66386. if (!_this._poster) {
  66387. _this._texture.dispose();
  66388. _this._texture = null;
  66389. }
  66390. };
  66391. _this._updateInternalTexture = function (e) {
  66392. if (_this._texture == null || !_this._texture.isReady) {
  66393. return;
  66394. }
  66395. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  66396. return;
  66397. }
  66398. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  66399. };
  66400. _this._engine = _this.getScene().getEngine();
  66401. _this._generateMipMaps = generateMipMaps;
  66402. _this._samplingMode = samplingMode;
  66403. _this.autoUpdateTexture = settings.autoUpdateTexture;
  66404. _this.name = name || _this._getName(src);
  66405. _this.video = _this._getVideo(src);
  66406. if (settings.poster) {
  66407. _this.video.poster = settings.poster;
  66408. }
  66409. if (settings.autoPlay !== undefined) {
  66410. _this.video.autoplay = settings.autoPlay;
  66411. }
  66412. if (settings.loop !== undefined) {
  66413. _this.video.loop = settings.loop;
  66414. }
  66415. _this.video.setAttribute("playsinline", "");
  66416. _this.video.addEventListener("canplay", _this._createInternalTexture);
  66417. _this.video.addEventListener("paused", _this._updateInternalTexture);
  66418. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  66419. _this.video.addEventListener("emptied", _this.reset);
  66420. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  66421. _this._createInternalTexture();
  66422. }
  66423. if (settings.poster) {
  66424. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  66425. _this._poster = true;
  66426. }
  66427. return _this;
  66428. }
  66429. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  66430. get: function () {
  66431. if (!this._onUserActionRequestedObservable) {
  66432. this._onUserActionRequestedObservable = new BABYLON.Observable();
  66433. }
  66434. return this._onUserActionRequestedObservable;
  66435. },
  66436. enumerable: true,
  66437. configurable: true
  66438. });
  66439. VideoTexture.prototype._getName = function (src) {
  66440. if (src instanceof HTMLVideoElement) {
  66441. return src.currentSrc;
  66442. }
  66443. if (typeof src === "object") {
  66444. return src.toString();
  66445. }
  66446. return src;
  66447. };
  66448. ;
  66449. VideoTexture.prototype._getVideo = function (src) {
  66450. if (src instanceof HTMLVideoElement) {
  66451. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  66452. return src;
  66453. }
  66454. var video = document.createElement("video");
  66455. if (typeof src === "string") {
  66456. BABYLON.Tools.SetCorsBehavior(src, video);
  66457. video.src = src;
  66458. }
  66459. else {
  66460. BABYLON.Tools.SetCorsBehavior(src[0], video);
  66461. src.forEach(function (url) {
  66462. var source = document.createElement("source");
  66463. source.src = url;
  66464. video.appendChild(source);
  66465. });
  66466. }
  66467. return video;
  66468. };
  66469. ;
  66470. /**
  66471. * Internal method to initiate `update`.
  66472. */
  66473. VideoTexture.prototype._rebuild = function () {
  66474. this.update();
  66475. };
  66476. /**
  66477. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  66478. */
  66479. VideoTexture.prototype.update = function () {
  66480. if (!this.autoUpdateTexture) {
  66481. // Expecting user to call `updateTexture` manually
  66482. return;
  66483. }
  66484. this.updateTexture(true);
  66485. };
  66486. /**
  66487. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  66488. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  66489. */
  66490. VideoTexture.prototype.updateTexture = function (isVisible) {
  66491. if (!isVisible) {
  66492. return;
  66493. }
  66494. if (this.video.paused && this._stillImageCaptured) {
  66495. return;
  66496. }
  66497. this._stillImageCaptured = true;
  66498. this._updateInternalTexture();
  66499. };
  66500. /**
  66501. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  66502. * @param url New url.
  66503. */
  66504. VideoTexture.prototype.updateURL = function (url) {
  66505. this.video.src = url;
  66506. };
  66507. VideoTexture.prototype.dispose = function () {
  66508. _super.prototype.dispose.call(this);
  66509. if (this._onUserActionRequestedObservable) {
  66510. this._onUserActionRequestedObservable.clear();
  66511. this._onUserActionRequestedObservable = null;
  66512. }
  66513. this.video.removeEventListener("canplay", this._createInternalTexture);
  66514. this.video.removeEventListener("paused", this._updateInternalTexture);
  66515. this.video.removeEventListener("seeked", this._updateInternalTexture);
  66516. this.video.removeEventListener("emptied", this.reset);
  66517. this.video.pause();
  66518. };
  66519. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  66520. var video = document.createElement("video");
  66521. video.setAttribute('autoplay', '');
  66522. video.setAttribute('muted', '');
  66523. video.setAttribute('playsinline', '');
  66524. var constraintsDeviceId;
  66525. if (constraints && constraints.deviceId) {
  66526. constraintsDeviceId = {
  66527. exact: constraints.deviceId,
  66528. };
  66529. }
  66530. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  66531. if (navigator.mediaDevices) {
  66532. navigator.mediaDevices.getUserMedia({ video: constraints })
  66533. .then(function (stream) {
  66534. if (video.mozSrcObject !== undefined) {
  66535. // hack for Firefox < 19
  66536. video.mozSrcObject = stream;
  66537. }
  66538. else {
  66539. video.srcObject = stream;
  66540. }
  66541. var onPlaying = function () {
  66542. if (onReady) {
  66543. onReady(new VideoTexture("video", video, scene, true, true));
  66544. }
  66545. video.removeEventListener("playing", onPlaying);
  66546. };
  66547. video.addEventListener("playing", onPlaying);
  66548. video.play();
  66549. })
  66550. .catch(function (err) {
  66551. BABYLON.Tools.Error(err.name);
  66552. });
  66553. }
  66554. else {
  66555. navigator.getUserMedia =
  66556. navigator.getUserMedia ||
  66557. navigator.webkitGetUserMedia ||
  66558. navigator.mozGetUserMedia ||
  66559. navigator.msGetUserMedia;
  66560. if (navigator.getUserMedia) {
  66561. navigator.getUserMedia({
  66562. video: {
  66563. deviceId: constraintsDeviceId,
  66564. width: {
  66565. min: (constraints && constraints.minWidth) || 256,
  66566. max: (constraints && constraints.maxWidth) || 640,
  66567. },
  66568. height: {
  66569. min: (constraints && constraints.minHeight) || 256,
  66570. max: (constraints && constraints.maxHeight) || 480,
  66571. },
  66572. },
  66573. }, function (stream) {
  66574. if (video.mozSrcObject !== undefined) {
  66575. // hack for Firefox < 19
  66576. video.mozSrcObject = stream;
  66577. }
  66578. else {
  66579. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  66580. }
  66581. video.play();
  66582. if (onReady) {
  66583. onReady(new VideoTexture("video", video, scene, true, true));
  66584. }
  66585. }, function (e) {
  66586. BABYLON.Tools.Error(e.name);
  66587. });
  66588. }
  66589. }
  66590. };
  66591. return VideoTexture;
  66592. }(BABYLON.Texture));
  66593. BABYLON.VideoTexture = VideoTexture;
  66594. })(BABYLON || (BABYLON = {}));
  66595. //# sourceMappingURL=babylon.videoTexture.js.map
  66596. var BABYLON;
  66597. (function (BABYLON) {
  66598. var RawTexture = /** @class */ (function (_super) {
  66599. __extends(RawTexture, _super);
  66600. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  66601. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66602. if (invertY === void 0) { invertY = false; }
  66603. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66604. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66605. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66606. _this.format = format;
  66607. _this._engine = scene.getEngine();
  66608. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  66609. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66610. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66611. return _this;
  66612. }
  66613. RawTexture.prototype.update = function (data) {
  66614. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66615. };
  66616. // Statics
  66617. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66618. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66619. if (invertY === void 0) { invertY = false; }
  66620. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66621. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  66622. };
  66623. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66624. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66625. if (invertY === void 0) { invertY = false; }
  66626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66627. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66628. };
  66629. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66630. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66631. if (invertY === void 0) { invertY = false; }
  66632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66633. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66634. };
  66635. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66636. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66637. if (invertY === void 0) { invertY = false; }
  66638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66639. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66640. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  66641. };
  66642. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66643. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66644. if (invertY === void 0) { invertY = false; }
  66645. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66646. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66647. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  66648. };
  66649. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66650. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66651. if (invertY === void 0) { invertY = false; }
  66652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66653. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66654. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  66655. };
  66656. return RawTexture;
  66657. }(BABYLON.Texture));
  66658. BABYLON.RawTexture = RawTexture;
  66659. })(BABYLON || (BABYLON = {}));
  66660. //# sourceMappingURL=babylon.rawTexture.js.map
  66661. var BABYLON;
  66662. (function (BABYLON) {
  66663. /**
  66664. * Class used to store 3D textures containing user data
  66665. */
  66666. var RawTexture3D = /** @class */ (function (_super) {
  66667. __extends(RawTexture3D, _super);
  66668. /**
  66669. * Create a new RawTexture3D
  66670. * @param data defines the data of the texture
  66671. * @param width defines the width of the texture
  66672. * @param height defines the height of the texture
  66673. * @param depth defines the depth of the texture
  66674. * @param format defines the texture format to use
  66675. * @param scene defines the hosting scene
  66676. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  66677. * @param invertY defines if texture must be stored with Y axis inverted
  66678. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  66679. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  66680. */
  66681. function RawTexture3D(data, width, height, depth,
  66682. /** Gets or sets the texture format to use */
  66683. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  66684. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66685. if (invertY === void 0) { invertY = false; }
  66686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66687. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66688. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66689. _this.format = format;
  66690. _this._engine = scene.getEngine();
  66691. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  66692. _this.is3D = true;
  66693. return _this;
  66694. }
  66695. /**
  66696. * Update the texture with new data
  66697. * @param data defines the data to store in the texture
  66698. */
  66699. RawTexture3D.prototype.update = function (data) {
  66700. if (!this._texture) {
  66701. return;
  66702. }
  66703. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66704. };
  66705. return RawTexture3D;
  66706. }(BABYLON.Texture));
  66707. BABYLON.RawTexture3D = RawTexture3D;
  66708. })(BABYLON || (BABYLON = {}));
  66709. //# sourceMappingURL=babylon.rawTexture3D.js.map
  66710. var BABYLON;
  66711. (function (BABYLON) {
  66712. /**
  66713. * PostProcessManager is used to manage one or more post processes or post process pipelines
  66714. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66715. */
  66716. var PostProcessManager = /** @class */ (function () {
  66717. /**
  66718. * Creates a new instance PostProcess
  66719. * @param scene The scene that the post process is associated with.
  66720. */
  66721. function PostProcessManager(scene) {
  66722. this._vertexBuffers = {};
  66723. this._scene = scene;
  66724. }
  66725. PostProcessManager.prototype._prepareBuffers = function () {
  66726. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  66727. return;
  66728. }
  66729. // VBO
  66730. var vertices = [];
  66731. vertices.push(1, 1);
  66732. vertices.push(-1, 1);
  66733. vertices.push(-1, -1);
  66734. vertices.push(1, -1);
  66735. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66736. this._buildIndexBuffer();
  66737. };
  66738. PostProcessManager.prototype._buildIndexBuffer = function () {
  66739. // Indices
  66740. var indices = [];
  66741. indices.push(0);
  66742. indices.push(1);
  66743. indices.push(2);
  66744. indices.push(0);
  66745. indices.push(2);
  66746. indices.push(3);
  66747. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  66748. };
  66749. /**
  66750. * Rebuilds the vertex buffers of the manager.
  66751. */
  66752. PostProcessManager.prototype._rebuild = function () {
  66753. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66754. if (!vb) {
  66755. return;
  66756. }
  66757. vb._rebuild();
  66758. this._buildIndexBuffer();
  66759. };
  66760. // Methods
  66761. /**
  66762. * Prepares a frame to be run through a post process.
  66763. * @param sourceTexture The input texture to the post procesess. (default: null)
  66764. * @param postProcesses An array of post processes to be run. (default: null)
  66765. * @returns True if the post processes were able to be run.
  66766. */
  66767. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  66768. if (sourceTexture === void 0) { sourceTexture = null; }
  66769. if (postProcesses === void 0) { postProcesses = null; }
  66770. var camera = this._scene.activeCamera;
  66771. if (!camera) {
  66772. return false;
  66773. }
  66774. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66775. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66776. return false;
  66777. }
  66778. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  66779. return true;
  66780. };
  66781. /**
  66782. * Manually render a set of post processes to a texture.
  66783. * @param postProcesses An array of post processes to be run.
  66784. * @param targetTexture The target texture to render to.
  66785. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  66786. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  66787. * @param lodLevel defines which lod of the texture to render to
  66788. */
  66789. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  66790. if (targetTexture === void 0) { targetTexture = null; }
  66791. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66792. if (faceIndex === void 0) { faceIndex = 0; }
  66793. if (lodLevel === void 0) { lodLevel = 0; }
  66794. var engine = this._scene.getEngine();
  66795. for (var index = 0; index < postProcesses.length; index++) {
  66796. if (index < postProcesses.length - 1) {
  66797. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  66798. }
  66799. else {
  66800. if (targetTexture) {
  66801. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  66802. }
  66803. else {
  66804. engine.restoreDefaultFramebuffer();
  66805. }
  66806. }
  66807. var pp = postProcesses[index];
  66808. var effect = pp.apply();
  66809. if (effect) {
  66810. pp.onBeforeRenderObservable.notifyObservers(effect);
  66811. // VBOs
  66812. this._prepareBuffers();
  66813. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66814. // Draw order
  66815. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66816. pp.onAfterRenderObservable.notifyObservers(effect);
  66817. }
  66818. }
  66819. // Restore depth buffer
  66820. engine.setDepthBuffer(true);
  66821. engine.setDepthWrite(true);
  66822. };
  66823. /**
  66824. * Finalize the result of the output of the postprocesses.
  66825. * @param doNotPresent If true the result will not be displayed to the screen.
  66826. * @param targetTexture The target texture to render to.
  66827. * @param faceIndex The index of the face to bind the target texture to.
  66828. * @param postProcesses The array of post processes to render.
  66829. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  66830. */
  66831. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  66832. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66833. var camera = this._scene.activeCamera;
  66834. if (!camera) {
  66835. return;
  66836. }
  66837. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66838. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66839. return;
  66840. }
  66841. var engine = this._scene.getEngine();
  66842. for (var index = 0, len = postProcesses.length; index < len; index++) {
  66843. var pp = postProcesses[index];
  66844. if (index < len - 1) {
  66845. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  66846. }
  66847. else {
  66848. if (targetTexture) {
  66849. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  66850. pp._outputTexture = targetTexture;
  66851. }
  66852. else {
  66853. engine.restoreDefaultFramebuffer();
  66854. pp._outputTexture = null;
  66855. }
  66856. }
  66857. if (doNotPresent) {
  66858. break;
  66859. }
  66860. var effect = pp.apply();
  66861. if (effect) {
  66862. pp.onBeforeRenderObservable.notifyObservers(effect);
  66863. // VBOs
  66864. this._prepareBuffers();
  66865. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66866. // Draw order
  66867. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66868. pp.onAfterRenderObservable.notifyObservers(effect);
  66869. }
  66870. }
  66871. // Restore states
  66872. engine.setDepthBuffer(true);
  66873. engine.setDepthWrite(true);
  66874. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66875. };
  66876. /**
  66877. * Disposes of the post process manager.
  66878. */
  66879. PostProcessManager.prototype.dispose = function () {
  66880. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66881. if (buffer) {
  66882. buffer.dispose();
  66883. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66884. }
  66885. if (this._indexBuffer) {
  66886. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66887. this._indexBuffer = null;
  66888. }
  66889. };
  66890. return PostProcessManager;
  66891. }());
  66892. BABYLON.PostProcessManager = PostProcessManager;
  66893. })(BABYLON || (BABYLON = {}));
  66894. //# sourceMappingURL=babylon.postProcessManager.js.map
  66895. var BABYLON;
  66896. (function (BABYLON) {
  66897. /**
  66898. * PostProcess can be used to apply a shader to a texture after it has been rendered
  66899. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66900. */
  66901. var PostProcess = /** @class */ (function () {
  66902. /**
  66903. * Creates a new instance PostProcess
  66904. * @param name The name of the PostProcess.
  66905. * @param fragmentUrl The url of the fragment shader to be used.
  66906. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  66907. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  66908. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  66909. * @param camera The camera to apply the render pass to.
  66910. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66911. * @param engine The engine which the post process will be applied. (default: current engine)
  66912. * @param reusable If the post process can be reused on the same frame. (default: false)
  66913. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  66914. * @param textureType Type of textures used when performing the post process. (default: 0)
  66915. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  66916. * @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
  66917. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  66918. */
  66919. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  66920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  66921. if (defines === void 0) { defines = null; }
  66922. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66923. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  66924. if (blockCompilation === void 0) { blockCompilation = false; }
  66925. this.name = name;
  66926. /**
  66927. * Width of the texture to apply the post process on
  66928. */
  66929. this.width = -1;
  66930. /**
  66931. * Height of the texture to apply the post process on
  66932. */
  66933. this.height = -1;
  66934. /**
  66935. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  66936. */
  66937. this._outputTexture = null;
  66938. /**
  66939. * If the buffer needs to be cleared before applying the post process. (default: true)
  66940. * Should be set to false if shader will overwrite all previous pixels.
  66941. */
  66942. this.autoClear = true;
  66943. /**
  66944. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  66945. */
  66946. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  66947. /**
  66948. * Animations to be used for the post processing
  66949. */
  66950. this.animations = new Array();
  66951. /**
  66952. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  66953. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  66954. */
  66955. this.enablePixelPerfectMode = false;
  66956. /**
  66957. * Force the postprocess to be applied without taking in account viewport
  66958. */
  66959. this.forceFullscreenViewport = true;
  66960. /**
  66961. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  66962. *
  66963. * | Value | Type | Description |
  66964. * | ----- | ----------------------------------- | ----------- |
  66965. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  66966. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  66967. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  66968. *
  66969. */
  66970. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  66971. /**
  66972. * Force textures to be a power of two (default: false)
  66973. */
  66974. this.alwaysForcePOT = false;
  66975. /**
  66976. * Number of sample textures (default: 1)
  66977. */
  66978. this.samples = 1;
  66979. /**
  66980. * Modify the scale of the post process to be the same as the viewport (default: false)
  66981. */
  66982. this.adaptScaleToCurrentViewport = false;
  66983. this._reusable = false;
  66984. /**
  66985. * Smart array of input and output textures for the post process.
  66986. */
  66987. this._textures = new BABYLON.SmartArray(2);
  66988. /**
  66989. * The index in _textures that corresponds to the output texture.
  66990. */
  66991. this._currentRenderTextureInd = 0;
  66992. this._scaleRatio = new BABYLON.Vector2(1, 1);
  66993. this._texelSize = BABYLON.Vector2.Zero();
  66994. // Events
  66995. /**
  66996. * An event triggered when the postprocess is activated.
  66997. */
  66998. this.onActivateObservable = new BABYLON.Observable();
  66999. /**
  67000. * An event triggered when the postprocess changes its size.
  67001. */
  67002. this.onSizeChangedObservable = new BABYLON.Observable();
  67003. /**
  67004. * An event triggered when the postprocess applies its effect.
  67005. */
  67006. this.onApplyObservable = new BABYLON.Observable();
  67007. /**
  67008. * An event triggered before rendering the postprocess
  67009. */
  67010. this.onBeforeRenderObservable = new BABYLON.Observable();
  67011. /**
  67012. * An event triggered after rendering the postprocess
  67013. */
  67014. this.onAfterRenderObservable = new BABYLON.Observable();
  67015. if (camera != null) {
  67016. this._camera = camera;
  67017. this._scene = camera.getScene();
  67018. camera.attachPostProcess(this);
  67019. this._engine = this._scene.getEngine();
  67020. this._scene.postProcesses.push(this);
  67021. }
  67022. else if (engine) {
  67023. this._engine = engine;
  67024. this._engine.postProcesses.push(this);
  67025. }
  67026. this._options = options;
  67027. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  67028. this._reusable = reusable || false;
  67029. this._textureType = textureType;
  67030. this._samplers = samplers || [];
  67031. this._samplers.push("textureSampler");
  67032. this._fragmentUrl = fragmentUrl;
  67033. this._vertexUrl = vertexUrl;
  67034. this._parameters = parameters || [];
  67035. this._parameters.push("scale");
  67036. this._indexParameters = indexParameters;
  67037. if (!blockCompilation) {
  67038. this.updateEffect(defines);
  67039. }
  67040. }
  67041. Object.defineProperty(PostProcess.prototype, "onActivate", {
  67042. /**
  67043. * A function that is added to the onActivateObservable
  67044. */
  67045. set: function (callback) {
  67046. if (this._onActivateObserver) {
  67047. this.onActivateObservable.remove(this._onActivateObserver);
  67048. }
  67049. if (callback) {
  67050. this._onActivateObserver = this.onActivateObservable.add(callback);
  67051. }
  67052. },
  67053. enumerable: true,
  67054. configurable: true
  67055. });
  67056. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  67057. /**
  67058. * A function that is added to the onSizeChangedObservable
  67059. */
  67060. set: function (callback) {
  67061. if (this._onSizeChangedObserver) {
  67062. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  67063. }
  67064. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  67065. },
  67066. enumerable: true,
  67067. configurable: true
  67068. });
  67069. Object.defineProperty(PostProcess.prototype, "onApply", {
  67070. /**
  67071. * A function that is added to the onApplyObservable
  67072. */
  67073. set: function (callback) {
  67074. if (this._onApplyObserver) {
  67075. this.onApplyObservable.remove(this._onApplyObserver);
  67076. }
  67077. this._onApplyObserver = this.onApplyObservable.add(callback);
  67078. },
  67079. enumerable: true,
  67080. configurable: true
  67081. });
  67082. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  67083. /**
  67084. * A function that is added to the onBeforeRenderObservable
  67085. */
  67086. set: function (callback) {
  67087. if (this._onBeforeRenderObserver) {
  67088. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67089. }
  67090. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67091. },
  67092. enumerable: true,
  67093. configurable: true
  67094. });
  67095. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  67096. /**
  67097. * A function that is added to the onAfterRenderObservable
  67098. */
  67099. set: function (callback) {
  67100. if (this._onAfterRenderObserver) {
  67101. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67102. }
  67103. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67104. },
  67105. enumerable: true,
  67106. configurable: true
  67107. });
  67108. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  67109. /**
  67110. * 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
  67111. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  67112. */
  67113. get: function () {
  67114. return this._textures.data[this._currentRenderTextureInd];
  67115. },
  67116. set: function (value) {
  67117. this._forcedOutputTexture = value;
  67118. },
  67119. enumerable: true,
  67120. configurable: true
  67121. });
  67122. /**
  67123. * Gets the camera which post process is applied to.
  67124. * @returns The camera the post process is applied to.
  67125. */
  67126. PostProcess.prototype.getCamera = function () {
  67127. return this._camera;
  67128. };
  67129. Object.defineProperty(PostProcess.prototype, "texelSize", {
  67130. /**
  67131. * Gets the texel size of the postprocess.
  67132. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  67133. */
  67134. get: function () {
  67135. if (this._shareOutputWithPostProcess) {
  67136. return this._shareOutputWithPostProcess.texelSize;
  67137. }
  67138. if (this._forcedOutputTexture) {
  67139. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  67140. }
  67141. return this._texelSize;
  67142. },
  67143. enumerable: true,
  67144. configurable: true
  67145. });
  67146. /**
  67147. * Gets the engine which this post process belongs to.
  67148. * @returns The engine the post process was enabled with.
  67149. */
  67150. PostProcess.prototype.getEngine = function () {
  67151. return this._engine;
  67152. };
  67153. /**
  67154. * The effect that is created when initializing the post process.
  67155. * @returns The created effect corrisponding the the postprocess.
  67156. */
  67157. PostProcess.prototype.getEffect = function () {
  67158. return this._effect;
  67159. };
  67160. /**
  67161. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  67162. * @param postProcess The post process to share the output with.
  67163. * @returns This post process.
  67164. */
  67165. PostProcess.prototype.shareOutputWith = function (postProcess) {
  67166. this._disposeTextures();
  67167. this._shareOutputWithPostProcess = postProcess;
  67168. return this;
  67169. };
  67170. /**
  67171. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  67172. * This should be called if the post process that shares output with this post process is disabled/disposed.
  67173. */
  67174. PostProcess.prototype.useOwnOutput = function () {
  67175. if (this._textures.length == 0) {
  67176. this._textures = new BABYLON.SmartArray(2);
  67177. }
  67178. this._shareOutputWithPostProcess = null;
  67179. };
  67180. /**
  67181. * Updates the effect with the current post process compile time values and recompiles the shader.
  67182. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  67183. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  67184. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  67185. * @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
  67186. * @param onCompiled Called when the shader has been compiled.
  67187. * @param onError Called if there is an error when compiling a shader.
  67188. */
  67189. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  67190. if (defines === void 0) { defines = null; }
  67191. if (uniforms === void 0) { uniforms = null; }
  67192. if (samplers === void 0) { samplers = null; }
  67193. 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);
  67194. };
  67195. /**
  67196. * The post process is reusable if it can be used multiple times within one frame.
  67197. * @returns If the post process is reusable
  67198. */
  67199. PostProcess.prototype.isReusable = function () {
  67200. return this._reusable;
  67201. };
  67202. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  67203. PostProcess.prototype.markTextureDirty = function () {
  67204. this.width = -1;
  67205. };
  67206. /**
  67207. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  67208. * 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.
  67209. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  67210. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  67211. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  67212. * @returns The target texture that was bound to be written to.
  67213. */
  67214. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  67215. var _this = this;
  67216. if (sourceTexture === void 0) { sourceTexture = null; }
  67217. camera = camera || this._camera;
  67218. var scene = camera.getScene();
  67219. var engine = scene.getEngine();
  67220. var maxSize = engine.getCaps().maxTextureSize;
  67221. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  67222. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  67223. // 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
  67224. var webVRCamera = camera.parent;
  67225. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  67226. requiredWidth /= 2;
  67227. }
  67228. var desiredWidth = (this._options.width || requiredWidth);
  67229. var desiredHeight = this._options.height || requiredHeight;
  67230. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  67231. if (this.adaptScaleToCurrentViewport) {
  67232. var currentViewport = engine.currentViewport;
  67233. if (currentViewport) {
  67234. desiredWidth *= currentViewport.width;
  67235. desiredHeight *= currentViewport.height;
  67236. }
  67237. }
  67238. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  67239. if (!this._options.width) {
  67240. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  67241. }
  67242. if (!this._options.height) {
  67243. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  67244. }
  67245. }
  67246. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  67247. if (this._textures.length > 0) {
  67248. for (var i = 0; i < this._textures.length; i++) {
  67249. this._engine._releaseTexture(this._textures.data[i]);
  67250. }
  67251. this._textures.reset();
  67252. }
  67253. this.width = desiredWidth;
  67254. this.height = desiredHeight;
  67255. var textureSize = { width: this.width, height: this.height };
  67256. var textureOptions = {
  67257. generateMipMaps: false,
  67258. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  67259. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  67260. samplingMode: this.renderTargetSamplingMode,
  67261. type: this._textureType
  67262. };
  67263. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67264. if (this._reusable) {
  67265. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67266. }
  67267. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  67268. this.onSizeChangedObservable.notifyObservers(this);
  67269. }
  67270. this._textures.forEach(function (texture) {
  67271. if (texture.samples !== _this.samples) {
  67272. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  67273. }
  67274. });
  67275. }
  67276. var target;
  67277. if (this._shareOutputWithPostProcess) {
  67278. target = this._shareOutputWithPostProcess.inputTexture;
  67279. }
  67280. else if (this._forcedOutputTexture) {
  67281. target = this._forcedOutputTexture;
  67282. this.width = this._forcedOutputTexture.width;
  67283. this.height = this._forcedOutputTexture.height;
  67284. }
  67285. else {
  67286. target = this.inputTexture;
  67287. }
  67288. // Bind the input of this post process to be used as the output of the previous post process.
  67289. if (this.enablePixelPerfectMode) {
  67290. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  67291. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  67292. }
  67293. else {
  67294. this._scaleRatio.copyFromFloats(1, 1);
  67295. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  67296. }
  67297. this.onActivateObservable.notifyObservers(camera);
  67298. // Clear
  67299. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  67300. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  67301. }
  67302. if (this._reusable) {
  67303. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  67304. }
  67305. return target;
  67306. };
  67307. Object.defineProperty(PostProcess.prototype, "isSupported", {
  67308. /**
  67309. * If the post process is supported.
  67310. */
  67311. get: function () {
  67312. return this._effect.isSupported;
  67313. },
  67314. enumerable: true,
  67315. configurable: true
  67316. });
  67317. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  67318. /**
  67319. * The aspect ratio of the output texture.
  67320. */
  67321. get: function () {
  67322. if (this._shareOutputWithPostProcess) {
  67323. return this._shareOutputWithPostProcess.aspectRatio;
  67324. }
  67325. if (this._forcedOutputTexture) {
  67326. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  67327. }
  67328. return this.width / this.height;
  67329. },
  67330. enumerable: true,
  67331. configurable: true
  67332. });
  67333. /**
  67334. * Get a value indicating if the post-process is ready to be used
  67335. * @returns true if the post-process is ready (shader is compiled)
  67336. */
  67337. PostProcess.prototype.isReady = function () {
  67338. return this._effect && this._effect.isReady();
  67339. };
  67340. /**
  67341. * Binds all textures and uniforms to the shader, this will be run on every pass.
  67342. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  67343. */
  67344. PostProcess.prototype.apply = function () {
  67345. // Check
  67346. if (!this._effect || !this._effect.isReady())
  67347. return null;
  67348. // States
  67349. this._engine.enableEffect(this._effect);
  67350. this._engine.setState(false);
  67351. this._engine.setDepthBuffer(false);
  67352. this._engine.setDepthWrite(false);
  67353. // Alpha
  67354. this._engine.setAlphaMode(this.alphaMode);
  67355. if (this.alphaConstants) {
  67356. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  67357. }
  67358. // Bind the output texture of the preivous post process as the input to this post process.
  67359. var source;
  67360. if (this._shareOutputWithPostProcess) {
  67361. source = this._shareOutputWithPostProcess.inputTexture;
  67362. }
  67363. else if (this._forcedOutputTexture) {
  67364. source = this._forcedOutputTexture;
  67365. }
  67366. else {
  67367. source = this.inputTexture;
  67368. }
  67369. this._effect._bindTexture("textureSampler", source);
  67370. // Parameters
  67371. this._effect.setVector2("scale", this._scaleRatio);
  67372. this.onApplyObservable.notifyObservers(this._effect);
  67373. return this._effect;
  67374. };
  67375. PostProcess.prototype._disposeTextures = function () {
  67376. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  67377. return;
  67378. }
  67379. if (this._textures.length > 0) {
  67380. for (var i = 0; i < this._textures.length; i++) {
  67381. this._engine._releaseTexture(this._textures.data[i]);
  67382. }
  67383. }
  67384. this._textures.dispose();
  67385. };
  67386. /**
  67387. * Disposes the post process.
  67388. * @param camera The camera to dispose the post process on.
  67389. */
  67390. PostProcess.prototype.dispose = function (camera) {
  67391. camera = camera || this._camera;
  67392. this._disposeTextures();
  67393. if (this._scene) {
  67394. var index_1 = this._scene.postProcesses.indexOf(this);
  67395. if (index_1 !== -1) {
  67396. this._scene.postProcesses.splice(index_1, 1);
  67397. }
  67398. }
  67399. else {
  67400. var index_2 = this._engine.postProcesses.indexOf(this);
  67401. if (index_2 !== -1) {
  67402. this._engine.postProcesses.splice(index_2, 1);
  67403. }
  67404. }
  67405. if (!camera) {
  67406. return;
  67407. }
  67408. camera.detachPostProcess(this);
  67409. var index = camera._postProcesses.indexOf(this);
  67410. if (index === 0 && camera._postProcesses.length > 0) {
  67411. var firstPostProcess = this._camera._getFirstPostProcess();
  67412. if (firstPostProcess) {
  67413. firstPostProcess.markTextureDirty();
  67414. }
  67415. }
  67416. this.onActivateObservable.clear();
  67417. this.onAfterRenderObservable.clear();
  67418. this.onApplyObservable.clear();
  67419. this.onBeforeRenderObservable.clear();
  67420. this.onSizeChangedObservable.clear();
  67421. };
  67422. return PostProcess;
  67423. }());
  67424. BABYLON.PostProcess = PostProcess;
  67425. })(BABYLON || (BABYLON = {}));
  67426. //# sourceMappingURL=babylon.postProcess.js.map
  67427. var BABYLON;
  67428. (function (BABYLON) {
  67429. var PassPostProcess = /** @class */ (function (_super) {
  67430. __extends(PassPostProcess, _super);
  67431. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67432. if (camera === void 0) { camera = null; }
  67433. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67434. if (blockCompilation === void 0) { blockCompilation = false; }
  67435. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  67436. }
  67437. return PassPostProcess;
  67438. }(BABYLON.PostProcess));
  67439. BABYLON.PassPostProcess = PassPostProcess;
  67440. })(BABYLON || (BABYLON = {}));
  67441. //# sourceMappingURL=babylon.passPostProcess.js.map
  67442. var __assign = (this && this.__assign) || Object.assign || function(t) {
  67443. for (var s, i = 1, n = arguments.length; i < n; i++) {
  67444. s = arguments[i];
  67445. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  67446. t[p] = s[p];
  67447. }
  67448. return t;
  67449. };
  67450. var BABYLON;
  67451. (function (BABYLON) {
  67452. /**
  67453. * Default implementation IShadowGenerator.
  67454. * This is the main object responsible of generating shadows in the framework.
  67455. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  67456. */
  67457. var ShadowGenerator = /** @class */ (function () {
  67458. /**
  67459. * Creates a ShadowGenerator object.
  67460. * A ShadowGenerator is the required tool to use the shadows.
  67461. * Each light casting shadows needs to use its own ShadowGenerator.
  67462. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  67463. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  67464. * @param light The light object generating the shadows.
  67465. * @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.
  67466. */
  67467. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  67468. this._bias = 0.00005;
  67469. this._normalBias = 0;
  67470. this._blurBoxOffset = 1;
  67471. this._blurScale = 2;
  67472. this._blurKernel = 1;
  67473. this._useKernelBlur = false;
  67474. this._filter = ShadowGenerator.FILTER_NONE;
  67475. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  67476. this._contactHardeningLightSizeUVRatio = 0.1;
  67477. this._darkness = 0;
  67478. this._transparencyShadow = false;
  67479. /**
  67480. * Controls the extent to which the shadows fade out at the edge of the frustum
  67481. * Used only by directionals and spots
  67482. */
  67483. this.frustumEdgeFalloff = 0;
  67484. /**
  67485. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  67486. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  67487. * It might on the other hand introduce peter panning.
  67488. */
  67489. this.forceBackFacesOnly = false;
  67490. this._lightDirection = BABYLON.Vector3.Zero();
  67491. this._viewMatrix = BABYLON.Matrix.Zero();
  67492. this._projectionMatrix = BABYLON.Matrix.Zero();
  67493. this._transformMatrix = BABYLON.Matrix.Zero();
  67494. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67495. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67496. this._currentFaceIndex = 0;
  67497. this._currentFaceIndexCache = 0;
  67498. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  67499. this._mapSize = mapSize;
  67500. this._light = light;
  67501. this._scene = light.getScene();
  67502. light._shadowGenerator = this;
  67503. // Texture type fallback from float to int if not supported.
  67504. var caps = this._scene.getEngine().getCaps();
  67505. if (!useFullFloatFirst) {
  67506. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67507. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67508. }
  67509. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67510. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67511. }
  67512. else {
  67513. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67514. }
  67515. }
  67516. else {
  67517. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67518. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67519. }
  67520. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67521. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67522. }
  67523. else {
  67524. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67525. }
  67526. }
  67527. this._initializeGenerator();
  67528. this._applyFilterValues();
  67529. }
  67530. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  67531. /**
  67532. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  67533. */
  67534. get: function () {
  67535. return this._bias;
  67536. },
  67537. /**
  67538. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  67539. */
  67540. set: function (bias) {
  67541. this._bias = bias;
  67542. },
  67543. enumerable: true,
  67544. configurable: true
  67545. });
  67546. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  67547. /**
  67548. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67549. */
  67550. get: function () {
  67551. return this._normalBias;
  67552. },
  67553. /**
  67554. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67555. */
  67556. set: function (normalBias) {
  67557. this._normalBias = normalBias;
  67558. },
  67559. enumerable: true,
  67560. configurable: true
  67561. });
  67562. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  67563. /**
  67564. * Gets the blur box offset: offset applied during the blur pass.
  67565. * Only usefull if useKernelBlur = false
  67566. */
  67567. get: function () {
  67568. return this._blurBoxOffset;
  67569. },
  67570. /**
  67571. * Sets the blur box offset: offset applied during the blur pass.
  67572. * Only usefull if useKernelBlur = false
  67573. */
  67574. set: function (value) {
  67575. if (this._blurBoxOffset === value) {
  67576. return;
  67577. }
  67578. this._blurBoxOffset = value;
  67579. this._disposeBlurPostProcesses();
  67580. },
  67581. enumerable: true,
  67582. configurable: true
  67583. });
  67584. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  67585. /**
  67586. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  67587. * 2 means half of the size.
  67588. */
  67589. get: function () {
  67590. return this._blurScale;
  67591. },
  67592. /**
  67593. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  67594. * 2 means half of the size.
  67595. */
  67596. set: function (value) {
  67597. if (this._blurScale === value) {
  67598. return;
  67599. }
  67600. this._blurScale = value;
  67601. this._disposeBlurPostProcesses();
  67602. },
  67603. enumerable: true,
  67604. configurable: true
  67605. });
  67606. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  67607. /**
  67608. * Gets the blur kernel: kernel size of the blur pass.
  67609. * Only usefull if useKernelBlur = true
  67610. */
  67611. get: function () {
  67612. return this._blurKernel;
  67613. },
  67614. /**
  67615. * Sets the blur kernel: kernel size of the blur pass.
  67616. * Only usefull if useKernelBlur = true
  67617. */
  67618. set: function (value) {
  67619. if (this._blurKernel === value) {
  67620. return;
  67621. }
  67622. this._blurKernel = value;
  67623. this._disposeBlurPostProcesses();
  67624. },
  67625. enumerable: true,
  67626. configurable: true
  67627. });
  67628. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  67629. /**
  67630. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  67631. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67632. */
  67633. get: function () {
  67634. return this._useKernelBlur;
  67635. },
  67636. /**
  67637. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  67638. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67639. */
  67640. set: function (value) {
  67641. if (this._useKernelBlur === value) {
  67642. return;
  67643. }
  67644. this._useKernelBlur = value;
  67645. this._disposeBlurPostProcesses();
  67646. },
  67647. enumerable: true,
  67648. configurable: true
  67649. });
  67650. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  67651. /**
  67652. * Gets the depth scale used in ESM mode.
  67653. */
  67654. get: function () {
  67655. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  67656. },
  67657. /**
  67658. * Sets the depth scale used in ESM mode.
  67659. * This can override the scale stored on the light.
  67660. */
  67661. set: function (value) {
  67662. this._depthScale = value;
  67663. },
  67664. enumerable: true,
  67665. configurable: true
  67666. });
  67667. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  67668. /**
  67669. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  67670. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67671. */
  67672. get: function () {
  67673. return this._filter;
  67674. },
  67675. /**
  67676. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  67677. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67678. */
  67679. set: function (value) {
  67680. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  67681. if (this._light.needCube()) {
  67682. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67683. this.useExponentialShadowMap = true;
  67684. return;
  67685. }
  67686. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67687. this.useCloseExponentialShadowMap = true;
  67688. return;
  67689. }
  67690. // PCF on cubemap would also be expensive
  67691. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67692. this.usePoissonSampling = true;
  67693. return;
  67694. }
  67695. }
  67696. // Weblg1 fallback for PCF.
  67697. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67698. if (this._scene.getEngine().webGLVersion === 1) {
  67699. this.usePoissonSampling = true;
  67700. return;
  67701. }
  67702. }
  67703. if (this._filter === value) {
  67704. return;
  67705. }
  67706. this._filter = value;
  67707. this._disposeBlurPostProcesses();
  67708. this._applyFilterValues();
  67709. this._light._markMeshesAsLightDirty();
  67710. },
  67711. enumerable: true,
  67712. configurable: true
  67713. });
  67714. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  67715. /**
  67716. * Gets if the current filter is set to Poisson Sampling.
  67717. */
  67718. get: function () {
  67719. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  67720. },
  67721. /**
  67722. * Sets the current filter to Poisson Sampling.
  67723. */
  67724. set: function (value) {
  67725. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  67726. return;
  67727. }
  67728. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  67729. },
  67730. enumerable: true,
  67731. configurable: true
  67732. });
  67733. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  67734. /**
  67735. * Gets if the current filter is set to VSM.
  67736. * DEPRECATED. Should use useExponentialShadowMap instead.
  67737. */
  67738. get: function () {
  67739. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67740. return this.useExponentialShadowMap;
  67741. },
  67742. /**
  67743. * Sets the current filter is to VSM.
  67744. * DEPRECATED. Should use useExponentialShadowMap instead.
  67745. */
  67746. set: function (value) {
  67747. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67748. this.useExponentialShadowMap = value;
  67749. },
  67750. enumerable: true,
  67751. configurable: true
  67752. });
  67753. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  67754. /**
  67755. * Gets if the current filter is set to blurred VSM.
  67756. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67757. */
  67758. get: function () {
  67759. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67760. return this.useBlurExponentialShadowMap;
  67761. },
  67762. /**
  67763. * Sets the current filter is to blurred VSM.
  67764. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67765. */
  67766. set: function (value) {
  67767. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67768. this.useBlurExponentialShadowMap = value;
  67769. },
  67770. enumerable: true,
  67771. configurable: true
  67772. });
  67773. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  67774. /**
  67775. * Gets if the current filter is set to ESM.
  67776. */
  67777. get: function () {
  67778. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  67779. },
  67780. /**
  67781. * Sets the current filter is to ESM.
  67782. */
  67783. set: function (value) {
  67784. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  67785. return;
  67786. }
  67787. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67788. },
  67789. enumerable: true,
  67790. configurable: true
  67791. });
  67792. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  67793. /**
  67794. * Gets if the current filter is set to filtered ESM.
  67795. */
  67796. get: function () {
  67797. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  67798. },
  67799. /**
  67800. * Gets if the current filter is set to filtered ESM.
  67801. */
  67802. set: function (value) {
  67803. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67804. return;
  67805. }
  67806. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67807. },
  67808. enumerable: true,
  67809. configurable: true
  67810. });
  67811. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  67812. /**
  67813. * Gets if the current filter is set to "close ESM" (using the inverse of the
  67814. * exponential to prevent steep falloff artifacts).
  67815. */
  67816. get: function () {
  67817. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  67818. },
  67819. /**
  67820. * Sets the current filter to "close ESM" (using the inverse of the
  67821. * exponential to prevent steep falloff artifacts).
  67822. */
  67823. set: function (value) {
  67824. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  67825. return;
  67826. }
  67827. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67828. },
  67829. enumerable: true,
  67830. configurable: true
  67831. });
  67832. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  67833. /**
  67834. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  67835. * exponential to prevent steep falloff artifacts).
  67836. */
  67837. get: function () {
  67838. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  67839. },
  67840. /**
  67841. * Sets the current filter to filtered "close ESM" (using the inverse of the
  67842. * exponential to prevent steep falloff artifacts).
  67843. */
  67844. set: function (value) {
  67845. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67846. return;
  67847. }
  67848. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67849. },
  67850. enumerable: true,
  67851. configurable: true
  67852. });
  67853. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  67854. /**
  67855. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  67856. */
  67857. get: function () {
  67858. return this.filter === ShadowGenerator.FILTER_PCF;
  67859. },
  67860. /**
  67861. * Sets the current filter to "PCF" (percentage closer filtering).
  67862. */
  67863. set: function (value) {
  67864. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  67865. return;
  67866. }
  67867. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  67868. },
  67869. enumerable: true,
  67870. configurable: true
  67871. });
  67872. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  67873. /**
  67874. * Gets the PCF or PCSS Quality.
  67875. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67876. */
  67877. get: function () {
  67878. return this._filteringQuality;
  67879. },
  67880. /**
  67881. * Sets the PCF or PCSS Quality.
  67882. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67883. */
  67884. set: function (filteringQuality) {
  67885. this._filteringQuality = filteringQuality;
  67886. },
  67887. enumerable: true,
  67888. configurable: true
  67889. });
  67890. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  67891. /**
  67892. * Gets if the current filter is set to "PCSS" (contact hardening).
  67893. */
  67894. get: function () {
  67895. return this.filter === ShadowGenerator.FILTER_PCSS;
  67896. },
  67897. /**
  67898. * Sets the current filter to "PCSS" (contact hardening).
  67899. */
  67900. set: function (value) {
  67901. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  67902. return;
  67903. }
  67904. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  67905. },
  67906. enumerable: true,
  67907. configurable: true
  67908. });
  67909. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  67910. /**
  67911. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67912. * Using a ratio helps keeping shape stability independently of the map size.
  67913. *
  67914. * It does not account for the light projection as it was having too much
  67915. * instability during the light setup or during light position changes.
  67916. *
  67917. * Only valid if useContactHardeningShadow is true.
  67918. */
  67919. get: function () {
  67920. return this._contactHardeningLightSizeUVRatio;
  67921. },
  67922. /**
  67923. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67924. * Using a ratio helps keeping shape stability independently of the map size.
  67925. *
  67926. * It does not account for the light projection as it was having too much
  67927. * instability during the light setup or during light position changes.
  67928. *
  67929. * Only valid if useContactHardeningShadow is true.
  67930. */
  67931. set: function (contactHardeningLightSizeUVRatio) {
  67932. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  67933. },
  67934. enumerable: true,
  67935. configurable: true
  67936. });
  67937. /**
  67938. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  67939. * 0 means strongest and 1 would means no shadow.
  67940. * @returns the darkness.
  67941. */
  67942. ShadowGenerator.prototype.getDarkness = function () {
  67943. return this._darkness;
  67944. };
  67945. /**
  67946. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  67947. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  67948. * @returns the shadow generator allowing fluent coding.
  67949. */
  67950. ShadowGenerator.prototype.setDarkness = function (darkness) {
  67951. if (darkness >= 1.0)
  67952. this._darkness = 1.0;
  67953. else if (darkness <= 0.0)
  67954. this._darkness = 0.0;
  67955. else
  67956. this._darkness = darkness;
  67957. return this;
  67958. };
  67959. /**
  67960. * Sets the ability to have transparent shadow (boolean).
  67961. * @param transparent True if transparent else False
  67962. * @returns the shadow generator allowing fluent coding
  67963. */
  67964. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  67965. this._transparencyShadow = transparent;
  67966. return this;
  67967. };
  67968. /**
  67969. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  67970. * @returns The render target texture if present otherwise, null
  67971. */
  67972. ShadowGenerator.prototype.getShadowMap = function () {
  67973. return this._shadowMap;
  67974. };
  67975. /**
  67976. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  67977. * @returns The render target texture if the shadow map is present otherwise, null
  67978. */
  67979. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  67980. if (this._shadowMap2) {
  67981. return this._shadowMap2;
  67982. }
  67983. return this._shadowMap;
  67984. };
  67985. /**
  67986. * Helper function to add a mesh and its descendants to the list of shadow casters.
  67987. * @param mesh Mesh to add
  67988. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  67989. * @returns the Shadow Generator itself
  67990. */
  67991. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  67992. if (includeDescendants === void 0) { includeDescendants = true; }
  67993. if (!this._shadowMap) {
  67994. return this;
  67995. }
  67996. if (!this._shadowMap.renderList) {
  67997. this._shadowMap.renderList = [];
  67998. }
  67999. this._shadowMap.renderList.push(mesh);
  68000. if (includeDescendants) {
  68001. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  68002. }
  68003. return this;
  68004. var _a;
  68005. };
  68006. /**
  68007. * Helper function to remove a mesh and its descendants from the list of shadow casters
  68008. * @param mesh Mesh to remove
  68009. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  68010. * @returns the Shadow Generator itself
  68011. */
  68012. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  68013. if (includeDescendants === void 0) { includeDescendants = true; }
  68014. if (!this._shadowMap || !this._shadowMap.renderList) {
  68015. return this;
  68016. }
  68017. var index = this._shadowMap.renderList.indexOf(mesh);
  68018. if (index !== -1) {
  68019. this._shadowMap.renderList.splice(index, 1);
  68020. }
  68021. if (includeDescendants) {
  68022. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  68023. var child = _a[_i];
  68024. this.removeShadowCaster(child);
  68025. }
  68026. }
  68027. return this;
  68028. };
  68029. /**
  68030. * Returns the associated light object.
  68031. * @returns the light generating the shadow
  68032. */
  68033. ShadowGenerator.prototype.getLight = function () {
  68034. return this._light;
  68035. };
  68036. ShadowGenerator.prototype._initializeGenerator = function () {
  68037. this._light._markMeshesAsLightDirty();
  68038. this._initializeShadowMap();
  68039. };
  68040. ShadowGenerator.prototype._initializeShadowMap = function () {
  68041. var _this = this;
  68042. // Render target
  68043. var engine = this._scene.getEngine();
  68044. if (engine.webGLVersion > 1) {
  68045. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  68046. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  68047. }
  68048. else {
  68049. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  68050. }
  68051. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68052. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68053. this._shadowMap.anisotropicFilteringLevel = 1;
  68054. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68055. this._shadowMap.renderParticles = false;
  68056. this._shadowMap.ignoreCameraViewport = true;
  68057. // Record Face Index before render.
  68058. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  68059. _this._currentFaceIndex = faceIndex;
  68060. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68061. engine.setColorWrite(false);
  68062. }
  68063. });
  68064. // Custom render function.
  68065. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  68066. // Blur if required afer render.
  68067. this._shadowMap.onAfterUnbindObservable.add(function () {
  68068. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68069. engine.setColorWrite(true);
  68070. }
  68071. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  68072. return;
  68073. }
  68074. var shadowMap = _this.getShadowMapForRendering();
  68075. if (shadowMap) {
  68076. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  68077. }
  68078. });
  68079. // Clear according to the chosen filter.
  68080. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  68081. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  68082. this._shadowMap.onClearObservable.add(function (engine) {
  68083. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68084. engine.clear(clearOne, false, true, false);
  68085. }
  68086. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  68087. engine.clear(clearZero, true, true, false);
  68088. }
  68089. else {
  68090. engine.clear(clearOne, true, true, false);
  68091. }
  68092. });
  68093. };
  68094. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  68095. var _this = this;
  68096. var engine = this._scene.getEngine();
  68097. var targetSize = this._mapSize / this.blurScale;
  68098. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  68099. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  68100. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68101. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68102. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68103. }
  68104. if (this.useKernelBlur) {
  68105. 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);
  68106. this._kernelBlurXPostprocess.width = targetSize;
  68107. this._kernelBlurXPostprocess.height = targetSize;
  68108. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  68109. effect.setTexture("textureSampler", _this._shadowMap);
  68110. });
  68111. 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);
  68112. this._kernelBlurXPostprocess.autoClear = false;
  68113. this._kernelBlurYPostprocess.autoClear = false;
  68114. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68115. this._kernelBlurXPostprocess.packedFloat = true;
  68116. this._kernelBlurYPostprocess.packedFloat = true;
  68117. }
  68118. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  68119. }
  68120. else {
  68121. 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);
  68122. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  68123. effect.setFloat2("screenSize", targetSize, targetSize);
  68124. effect.setTexture("textureSampler", _this._shadowMap);
  68125. });
  68126. this._boxBlurPostprocess.autoClear = false;
  68127. this._blurPostProcesses = [this._boxBlurPostprocess];
  68128. }
  68129. };
  68130. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68131. var index;
  68132. var engine = this._scene.getEngine();
  68133. if (depthOnlySubMeshes.length) {
  68134. engine.setColorWrite(false);
  68135. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68136. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  68137. }
  68138. engine.setColorWrite(true);
  68139. }
  68140. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68141. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  68142. }
  68143. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68144. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  68145. }
  68146. if (this._transparencyShadow) {
  68147. for (index = 0; index < transparentSubMeshes.length; index++) {
  68148. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  68149. }
  68150. }
  68151. };
  68152. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  68153. var _this = this;
  68154. var mesh = subMesh.getRenderingMesh();
  68155. var scene = this._scene;
  68156. var engine = scene.getEngine();
  68157. var material = subMesh.getMaterial();
  68158. if (!material) {
  68159. return;
  68160. }
  68161. // Culling
  68162. engine.setState(material.backFaceCulling);
  68163. // Managing instances
  68164. var batch = mesh._getInstancesRenderList(subMesh._id);
  68165. if (batch.mustReturn) {
  68166. return;
  68167. }
  68168. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68169. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  68170. engine.enableEffect(this._effect);
  68171. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68172. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  68173. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  68174. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68175. this._effect.setVector3("lightData", this._cachedDirection);
  68176. }
  68177. else {
  68178. this._effect.setVector3("lightData", this._cachedPosition);
  68179. }
  68180. if (scene.activeCamera) {
  68181. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  68182. }
  68183. // Alpha test
  68184. if (material && material.needAlphaTesting()) {
  68185. var alphaTexture = material.getAlphaTestTexture();
  68186. if (alphaTexture) {
  68187. this._effect.setTexture("diffuseSampler", alphaTexture);
  68188. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  68189. }
  68190. }
  68191. // Bones
  68192. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68193. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  68194. }
  68195. // Morph targets
  68196. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  68197. if (this.forceBackFacesOnly) {
  68198. engine.setState(true, 0, false, true);
  68199. }
  68200. // Draw
  68201. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68202. if (this.forceBackFacesOnly) {
  68203. engine.setState(true, 0, false, false);
  68204. }
  68205. }
  68206. else {
  68207. // Need to reset refresh rate of the shadowMap
  68208. if (this._shadowMap) {
  68209. this._shadowMap.resetRefreshCounter();
  68210. }
  68211. }
  68212. };
  68213. ShadowGenerator.prototype._applyFilterValues = function () {
  68214. if (!this._shadowMap) {
  68215. return;
  68216. }
  68217. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  68218. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  68219. }
  68220. else {
  68221. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68222. }
  68223. };
  68224. /**
  68225. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68226. * @param onCompiled Callback triggered at the and of the effects compilation
  68227. * @param options Sets of optional options forcing the compilation with different modes
  68228. */
  68229. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  68230. var _this = this;
  68231. var localOptions = __assign({ useInstances: false }, options);
  68232. var shadowMap = this.getShadowMap();
  68233. if (!shadowMap) {
  68234. if (onCompiled) {
  68235. onCompiled(this);
  68236. }
  68237. return;
  68238. }
  68239. var renderList = shadowMap.renderList;
  68240. if (!renderList) {
  68241. if (onCompiled) {
  68242. onCompiled(this);
  68243. }
  68244. return;
  68245. }
  68246. var subMeshes = new Array();
  68247. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  68248. var mesh = renderList_1[_i];
  68249. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  68250. }
  68251. if (subMeshes.length === 0) {
  68252. if (onCompiled) {
  68253. onCompiled(this);
  68254. }
  68255. return;
  68256. }
  68257. var currentIndex = 0;
  68258. var checkReady = function () {
  68259. if (!_this._scene || !_this._scene.getEngine()) {
  68260. return;
  68261. }
  68262. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  68263. currentIndex++;
  68264. if (currentIndex >= subMeshes.length) {
  68265. if (onCompiled) {
  68266. onCompiled(_this);
  68267. }
  68268. return;
  68269. }
  68270. }
  68271. setTimeout(checkReady, 16);
  68272. };
  68273. checkReady();
  68274. };
  68275. /**
  68276. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68277. * @param options Sets of optional options forcing the compilation with different modes
  68278. * @returns A promise that resolves when the compilation completes
  68279. */
  68280. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  68281. var _this = this;
  68282. return new Promise(function (resolve) {
  68283. _this.forceCompilation(function () {
  68284. resolve();
  68285. }, options);
  68286. });
  68287. };
  68288. /**
  68289. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  68290. * @param subMesh The submesh we want to render in the shadow map
  68291. * @param useInstances Defines wether will draw in the map using instances
  68292. * @returns true if ready otherwise, false
  68293. */
  68294. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  68295. var defines = [];
  68296. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68297. defines.push("#define FLOAT");
  68298. }
  68299. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68300. defines.push("#define ESM");
  68301. }
  68302. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  68303. defines.push("#define DEPTHTEXTURE");
  68304. }
  68305. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68306. var mesh = subMesh.getMesh();
  68307. var material = subMesh.getMaterial();
  68308. // Normal bias.
  68309. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68310. attribs.push(BABYLON.VertexBuffer.NormalKind);
  68311. defines.push("#define NORMAL");
  68312. if (mesh.nonUniformScaling) {
  68313. defines.push("#define NONUNIFORMSCALING");
  68314. }
  68315. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68316. defines.push("#define DIRECTIONINLIGHTDATA");
  68317. }
  68318. }
  68319. // Alpha test
  68320. if (material && material.needAlphaTesting()) {
  68321. var alphaTexture = material.getAlphaTestTexture();
  68322. if (alphaTexture) {
  68323. defines.push("#define ALPHATEST");
  68324. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68325. attribs.push(BABYLON.VertexBuffer.UVKind);
  68326. defines.push("#define UV1");
  68327. }
  68328. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68329. if (alphaTexture.coordinatesIndex === 1) {
  68330. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68331. defines.push("#define UV2");
  68332. }
  68333. }
  68334. }
  68335. }
  68336. // Bones
  68337. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68338. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68339. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68340. if (mesh.numBoneInfluencers > 4) {
  68341. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68342. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68343. }
  68344. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68345. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68346. }
  68347. else {
  68348. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68349. }
  68350. // Morph targets
  68351. var manager = mesh.morphTargetManager;
  68352. var morphInfluencers = 0;
  68353. if (manager) {
  68354. if (manager.numInfluencers > 0) {
  68355. defines.push("#define MORPHTARGETS");
  68356. morphInfluencers = manager.numInfluencers;
  68357. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  68358. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  68359. }
  68360. }
  68361. // Instances
  68362. if (useInstances) {
  68363. defines.push("#define INSTANCES");
  68364. attribs.push("world0");
  68365. attribs.push("world1");
  68366. attribs.push("world2");
  68367. attribs.push("world3");
  68368. }
  68369. // Get correct effect
  68370. var join = defines.join("\n");
  68371. if (this._cachedDefines !== join) {
  68372. this._cachedDefines = join;
  68373. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  68374. }
  68375. if (!this._effect.isReady()) {
  68376. return false;
  68377. }
  68378. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68379. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  68380. this._initializeBlurRTTAndPostProcesses();
  68381. }
  68382. }
  68383. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  68384. return false;
  68385. }
  68386. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  68387. return false;
  68388. }
  68389. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  68390. return false;
  68391. }
  68392. return true;
  68393. };
  68394. /**
  68395. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  68396. * @param defines Defines of the material we want to update
  68397. * @param lightIndex Index of the light in the enabled light list of the material
  68398. */
  68399. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  68400. var scene = this._scene;
  68401. var light = this._light;
  68402. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68403. return;
  68404. }
  68405. defines["SHADOW" + lightIndex] = true;
  68406. if (this.useContactHardeningShadow) {
  68407. defines["SHADOWPCSS" + lightIndex] = true;
  68408. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68409. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68410. }
  68411. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68412. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68413. }
  68414. // else default to high.
  68415. }
  68416. if (this.usePercentageCloserFiltering) {
  68417. defines["SHADOWPCF" + lightIndex] = true;
  68418. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68419. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68420. }
  68421. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68422. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68423. }
  68424. // else default to high.
  68425. }
  68426. else if (this.usePoissonSampling) {
  68427. defines["SHADOWPOISSON" + lightIndex] = true;
  68428. }
  68429. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68430. defines["SHADOWESM" + lightIndex] = true;
  68431. }
  68432. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68433. defines["SHADOWCLOSEESM" + lightIndex] = true;
  68434. }
  68435. if (light.needCube()) {
  68436. defines["SHADOWCUBE" + lightIndex] = true;
  68437. }
  68438. };
  68439. /**
  68440. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  68441. * defined in the generator but impacting the effect).
  68442. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  68443. * @param effect The effect we are binfing the information for
  68444. */
  68445. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  68446. var light = this._light;
  68447. var scene = this._scene;
  68448. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68449. return;
  68450. }
  68451. var camera = scene.activeCamera;
  68452. if (!camera) {
  68453. return;
  68454. }
  68455. var shadowMap = this.getShadowMap();
  68456. if (!shadowMap) {
  68457. return;
  68458. }
  68459. if (!light.needCube()) {
  68460. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  68461. }
  68462. // Only PCF uses depth stencil texture.
  68463. if (this._filter === ShadowGenerator.FILTER_PCF) {
  68464. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68465. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68466. }
  68467. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  68468. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68469. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  68470. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68471. }
  68472. else {
  68473. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68474. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  68475. }
  68476. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  68477. };
  68478. /**
  68479. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  68480. * (eq to shadow prjection matrix * light transform matrix)
  68481. * @returns The transform matrix used to create the shadow map
  68482. */
  68483. ShadowGenerator.prototype.getTransformMatrix = function () {
  68484. var scene = this._scene;
  68485. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  68486. return this._transformMatrix;
  68487. }
  68488. this._currentRenderID = scene.getRenderId();
  68489. this._currentFaceIndexCache = this._currentFaceIndex;
  68490. var lightPosition = this._light.position;
  68491. if (this._light.computeTransformedInformation()) {
  68492. lightPosition = this._light.transformedPosition;
  68493. }
  68494. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  68495. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  68496. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  68497. }
  68498. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  68499. this._cachedPosition.copyFrom(lightPosition);
  68500. this._cachedDirection.copyFrom(this._lightDirection);
  68501. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  68502. var shadowMap = this.getShadowMap();
  68503. if (shadowMap) {
  68504. var renderList = shadowMap.renderList;
  68505. if (renderList) {
  68506. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  68507. }
  68508. }
  68509. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  68510. }
  68511. return this._transformMatrix;
  68512. };
  68513. /**
  68514. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  68515. * Cube and 2D textures for instance.
  68516. */
  68517. ShadowGenerator.prototype.recreateShadowMap = function () {
  68518. var shadowMap = this._shadowMap;
  68519. if (!shadowMap) {
  68520. return;
  68521. }
  68522. // Track render list.
  68523. var renderList = shadowMap.renderList;
  68524. // Clean up existing data.
  68525. this._disposeRTTandPostProcesses();
  68526. // Reinitializes.
  68527. this._initializeGenerator();
  68528. // Reaffect the filter to ensure a correct fallback if necessary.
  68529. this.filter = this.filter;
  68530. // Reaffect the filter.
  68531. this._applyFilterValues();
  68532. // Reaffect Render List.
  68533. this._shadowMap.renderList = renderList;
  68534. };
  68535. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  68536. if (this._shadowMap2) {
  68537. this._shadowMap2.dispose();
  68538. this._shadowMap2 = null;
  68539. }
  68540. if (this._boxBlurPostprocess) {
  68541. this._boxBlurPostprocess.dispose();
  68542. this._boxBlurPostprocess = null;
  68543. }
  68544. if (this._kernelBlurXPostprocess) {
  68545. this._kernelBlurXPostprocess.dispose();
  68546. this._kernelBlurXPostprocess = null;
  68547. }
  68548. if (this._kernelBlurYPostprocess) {
  68549. this._kernelBlurYPostprocess.dispose();
  68550. this._kernelBlurYPostprocess = null;
  68551. }
  68552. this._blurPostProcesses = [];
  68553. };
  68554. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  68555. if (this._shadowMap) {
  68556. this._shadowMap.dispose();
  68557. this._shadowMap = null;
  68558. }
  68559. this._disposeBlurPostProcesses();
  68560. };
  68561. /**
  68562. * Disposes the ShadowGenerator.
  68563. * Returns nothing.
  68564. */
  68565. ShadowGenerator.prototype.dispose = function () {
  68566. this._disposeRTTandPostProcesses();
  68567. if (this._light) {
  68568. this._light._shadowGenerator = null;
  68569. this._light._markMeshesAsLightDirty();
  68570. }
  68571. };
  68572. /**
  68573. * Serializes the shadow generator setup to a json object.
  68574. * @returns The serialized JSON object
  68575. */
  68576. ShadowGenerator.prototype.serialize = function () {
  68577. var serializationObject = {};
  68578. var shadowMap = this.getShadowMap();
  68579. if (!shadowMap) {
  68580. return serializationObject;
  68581. }
  68582. serializationObject.lightId = this._light.id;
  68583. serializationObject.mapSize = shadowMap.getRenderSize();
  68584. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  68585. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  68586. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68587. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68588. serializationObject.usePoissonSampling = this.usePoissonSampling;
  68589. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  68590. serializationObject.depthScale = this.depthScale;
  68591. serializationObject.darkness = this.getDarkness();
  68592. serializationObject.blurBoxOffset = this.blurBoxOffset;
  68593. serializationObject.blurKernel = this.blurKernel;
  68594. serializationObject.blurScale = this.blurScale;
  68595. serializationObject.useKernelBlur = this.useKernelBlur;
  68596. serializationObject.transparencyShadow = this._transparencyShadow;
  68597. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  68598. serializationObject.bias = this.bias;
  68599. serializationObject.normalBias = this.normalBias;
  68600. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  68601. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  68602. serializationObject.filteringQuality = this.filteringQuality;
  68603. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  68604. serializationObject.renderList = [];
  68605. if (shadowMap.renderList) {
  68606. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  68607. var mesh = shadowMap.renderList[meshIndex];
  68608. serializationObject.renderList.push(mesh.id);
  68609. }
  68610. }
  68611. return serializationObject;
  68612. };
  68613. /**
  68614. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  68615. * @param parsedShadowGenerator The JSON object to parse
  68616. * @param scene The scene to create the shadow map for
  68617. * @returns The parsed shadow generator
  68618. */
  68619. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  68620. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  68621. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  68622. var shadowMap = shadowGenerator.getShadowMap();
  68623. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  68624. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  68625. meshes.forEach(function (mesh) {
  68626. if (!shadowMap) {
  68627. return;
  68628. }
  68629. if (!shadowMap.renderList) {
  68630. shadowMap.renderList = [];
  68631. }
  68632. shadowMap.renderList.push(mesh);
  68633. });
  68634. }
  68635. if (parsedShadowGenerator.usePoissonSampling) {
  68636. shadowGenerator.usePoissonSampling = true;
  68637. }
  68638. else if (parsedShadowGenerator.useExponentialShadowMap) {
  68639. shadowGenerator.useExponentialShadowMap = true;
  68640. }
  68641. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  68642. shadowGenerator.useBlurExponentialShadowMap = true;
  68643. }
  68644. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  68645. shadowGenerator.useCloseExponentialShadowMap = true;
  68646. }
  68647. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  68648. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  68649. }
  68650. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  68651. shadowGenerator.usePercentageCloserFiltering = true;
  68652. }
  68653. else if (parsedShadowGenerator.useContactHardeningShadow) {
  68654. shadowGenerator.useContactHardeningShadow = true;
  68655. }
  68656. if (parsedShadowGenerator.filteringQuality) {
  68657. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  68658. }
  68659. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  68660. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  68661. }
  68662. // Backward compat
  68663. else if (parsedShadowGenerator.useVarianceShadowMap) {
  68664. shadowGenerator.useExponentialShadowMap = true;
  68665. }
  68666. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  68667. shadowGenerator.useBlurExponentialShadowMap = true;
  68668. }
  68669. if (parsedShadowGenerator.depthScale) {
  68670. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  68671. }
  68672. if (parsedShadowGenerator.blurScale) {
  68673. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  68674. }
  68675. if (parsedShadowGenerator.blurBoxOffset) {
  68676. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  68677. }
  68678. if (parsedShadowGenerator.useKernelBlur) {
  68679. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  68680. }
  68681. if (parsedShadowGenerator.blurKernel) {
  68682. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  68683. }
  68684. if (parsedShadowGenerator.bias !== undefined) {
  68685. shadowGenerator.bias = parsedShadowGenerator.bias;
  68686. }
  68687. if (parsedShadowGenerator.normalBias !== undefined) {
  68688. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  68689. }
  68690. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  68691. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  68692. }
  68693. if (parsedShadowGenerator.darkness) {
  68694. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  68695. }
  68696. if (parsedShadowGenerator.transparencyShadow) {
  68697. shadowGenerator.setTransparencyShadow(true);
  68698. }
  68699. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  68700. return shadowGenerator;
  68701. };
  68702. /**
  68703. * Shadow generator mode None: no filtering applied.
  68704. */
  68705. ShadowGenerator.FILTER_NONE = 0;
  68706. /**
  68707. * Shadow generator mode ESM: Exponential Shadow Mapping.
  68708. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68709. */
  68710. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  68711. /**
  68712. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  68713. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  68714. */
  68715. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  68716. /**
  68717. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  68718. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68719. */
  68720. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  68721. /**
  68722. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  68723. * edge artifacts on steep falloff.
  68724. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68725. */
  68726. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  68727. /**
  68728. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  68729. * edge artifacts on steep falloff.
  68730. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68731. */
  68732. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  68733. /**
  68734. * Shadow generator mode PCF: Percentage Closer Filtering
  68735. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68736. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  68737. */
  68738. ShadowGenerator.FILTER_PCF = 6;
  68739. /**
  68740. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  68741. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68742. * Contact Hardening
  68743. */
  68744. ShadowGenerator.FILTER_PCSS = 7;
  68745. /**
  68746. * Reserved for PCF and PCSS
  68747. * Highest Quality.
  68748. *
  68749. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  68750. *
  68751. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  68752. */
  68753. ShadowGenerator.QUALITY_HIGH = 0;
  68754. /**
  68755. * Reserved for PCF and PCSS
  68756. * Good tradeoff for quality/perf cross devices
  68757. *
  68758. * Execute PCF on a 3*3 kernel.
  68759. *
  68760. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  68761. */
  68762. ShadowGenerator.QUALITY_MEDIUM = 1;
  68763. /**
  68764. * Reserved for PCF and PCSS
  68765. * The lowest quality but the fastest.
  68766. *
  68767. * Execute PCF on a 1*1 kernel.
  68768. *
  68769. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  68770. */
  68771. ShadowGenerator.QUALITY_LOW = 2;
  68772. return ShadowGenerator;
  68773. }());
  68774. BABYLON.ShadowGenerator = ShadowGenerator;
  68775. })(BABYLON || (BABYLON = {}));
  68776. //# sourceMappingURL=babylon.shadowGenerator.js.map
  68777. var BABYLON;
  68778. (function (BABYLON) {
  68779. var DefaultLoadingScreen = /** @class */ (function () {
  68780. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  68781. if (_loadingText === void 0) { _loadingText = ""; }
  68782. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  68783. var _this = this;
  68784. this._renderingCanvas = _renderingCanvas;
  68785. this._loadingText = _loadingText;
  68786. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  68787. // Resize
  68788. this._resizeLoadingUI = function () {
  68789. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  68790. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  68791. if (!_this._loadingDiv) {
  68792. return;
  68793. }
  68794. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  68795. _this._loadingDiv.style.left = canvasRect.left + "px";
  68796. _this._loadingDiv.style.top = canvasRect.top + "px";
  68797. _this._loadingDiv.style.width = canvasRect.width + "px";
  68798. _this._loadingDiv.style.height = canvasRect.height + "px";
  68799. };
  68800. }
  68801. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  68802. if (this._loadingDiv) {
  68803. // Do not add a loading screen if there is already one
  68804. return;
  68805. }
  68806. this._loadingDiv = document.createElement("div");
  68807. this._loadingDiv.id = "babylonjsLoadingDiv";
  68808. this._loadingDiv.style.opacity = "0";
  68809. this._loadingDiv.style.transition = "opacity 1.5s ease";
  68810. this._loadingDiv.style.pointerEvents = "none";
  68811. // Loading text
  68812. this._loadingTextDiv = document.createElement("div");
  68813. this._loadingTextDiv.style.position = "absolute";
  68814. this._loadingTextDiv.style.left = "0";
  68815. this._loadingTextDiv.style.top = "50%";
  68816. this._loadingTextDiv.style.marginTop = "80px";
  68817. this._loadingTextDiv.style.width = "100%";
  68818. this._loadingTextDiv.style.height = "20px";
  68819. this._loadingTextDiv.style.fontFamily = "Arial";
  68820. this._loadingTextDiv.style.fontSize = "14px";
  68821. this._loadingTextDiv.style.color = "white";
  68822. this._loadingTextDiv.style.textAlign = "center";
  68823. this._loadingTextDiv.innerHTML = "Loading";
  68824. this._loadingDiv.appendChild(this._loadingTextDiv);
  68825. //set the predefined text
  68826. this._loadingTextDiv.innerHTML = this._loadingText;
  68827. // Generating keyframes
  68828. var style = document.createElement('style');
  68829. style.type = 'text/css';
  68830. 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 }";
  68831. style.innerHTML = keyFrames;
  68832. document.getElementsByTagName('head')[0].appendChild(style);
  68833. // Loading img
  68834. var imgBack = new Image();
  68835. 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";
  68836. imgBack.style.position = "absolute";
  68837. imgBack.style.left = "50%";
  68838. imgBack.style.top = "50%";
  68839. imgBack.style.marginLeft = "-60px";
  68840. imgBack.style.marginTop = "-60px";
  68841. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  68842. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  68843. imgBack.style.transformOrigin = "50% 50%";
  68844. imgBack.style.webkitTransformOrigin = "50% 50%";
  68845. this._loadingDiv.appendChild(imgBack);
  68846. this._resizeLoadingUI();
  68847. window.addEventListener("resize", this._resizeLoadingUI);
  68848. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68849. document.body.appendChild(this._loadingDiv);
  68850. this._loadingDiv.style.opacity = "1";
  68851. };
  68852. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  68853. var _this = this;
  68854. if (!this._loadingDiv) {
  68855. return;
  68856. }
  68857. var onTransitionEnd = function () {
  68858. if (!_this._loadingDiv) {
  68859. return;
  68860. }
  68861. document.body.removeChild(_this._loadingDiv);
  68862. window.removeEventListener("resize", _this._resizeLoadingUI);
  68863. _this._loadingDiv = null;
  68864. };
  68865. this._loadingDiv.style.opacity = "0";
  68866. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  68867. };
  68868. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  68869. set: function (text) {
  68870. this._loadingText = text;
  68871. if (this._loadingTextDiv) {
  68872. this._loadingTextDiv.innerHTML = this._loadingText;
  68873. }
  68874. },
  68875. enumerable: true,
  68876. configurable: true
  68877. });
  68878. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  68879. get: function () {
  68880. return this._loadingDivBackgroundColor;
  68881. },
  68882. set: function (color) {
  68883. this._loadingDivBackgroundColor = color;
  68884. if (!this._loadingDiv) {
  68885. return;
  68886. }
  68887. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68888. },
  68889. enumerable: true,
  68890. configurable: true
  68891. });
  68892. return DefaultLoadingScreen;
  68893. }());
  68894. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  68895. })(BABYLON || (BABYLON = {}));
  68896. //# sourceMappingURL=babylon.loadingScreen.js.map
  68897. var BABYLON;
  68898. (function (BABYLON) {
  68899. var SceneLoaderProgressEvent = /** @class */ (function () {
  68900. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  68901. this.lengthComputable = lengthComputable;
  68902. this.loaded = loaded;
  68903. this.total = total;
  68904. }
  68905. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  68906. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  68907. };
  68908. return SceneLoaderProgressEvent;
  68909. }());
  68910. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  68911. var SceneLoader = /** @class */ (function () {
  68912. function SceneLoader() {
  68913. }
  68914. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  68915. get: function () {
  68916. return 0;
  68917. },
  68918. enumerable: true,
  68919. configurable: true
  68920. });
  68921. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  68922. get: function () {
  68923. return 1;
  68924. },
  68925. enumerable: true,
  68926. configurable: true
  68927. });
  68928. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  68929. get: function () {
  68930. return 2;
  68931. },
  68932. enumerable: true,
  68933. configurable: true
  68934. });
  68935. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  68936. get: function () {
  68937. return 3;
  68938. },
  68939. enumerable: true,
  68940. configurable: true
  68941. });
  68942. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  68943. get: function () {
  68944. return SceneLoader._ForceFullSceneLoadingForIncremental;
  68945. },
  68946. set: function (value) {
  68947. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  68948. },
  68949. enumerable: true,
  68950. configurable: true
  68951. });
  68952. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  68953. get: function () {
  68954. return SceneLoader._ShowLoadingScreen;
  68955. },
  68956. set: function (value) {
  68957. SceneLoader._ShowLoadingScreen = value;
  68958. },
  68959. enumerable: true,
  68960. configurable: true
  68961. });
  68962. Object.defineProperty(SceneLoader, "loggingLevel", {
  68963. get: function () {
  68964. return SceneLoader._loggingLevel;
  68965. },
  68966. set: function (value) {
  68967. SceneLoader._loggingLevel = value;
  68968. },
  68969. enumerable: true,
  68970. configurable: true
  68971. });
  68972. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  68973. get: function () {
  68974. return SceneLoader._CleanBoneMatrixWeights;
  68975. },
  68976. set: function (value) {
  68977. SceneLoader._CleanBoneMatrixWeights = value;
  68978. },
  68979. enumerable: true,
  68980. configurable: true
  68981. });
  68982. SceneLoader._getDefaultPlugin = function () {
  68983. return SceneLoader._registeredPlugins[".babylon"];
  68984. };
  68985. SceneLoader._getPluginForExtension = function (extension) {
  68986. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  68987. if (registeredPlugin) {
  68988. return registeredPlugin;
  68989. }
  68990. 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");
  68991. return SceneLoader._getDefaultPlugin();
  68992. };
  68993. SceneLoader._getPluginForDirectLoad = function (data) {
  68994. for (var extension in SceneLoader._registeredPlugins) {
  68995. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  68996. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  68997. return SceneLoader._registeredPlugins[extension];
  68998. }
  68999. }
  69000. return SceneLoader._getDefaultPlugin();
  69001. };
  69002. SceneLoader._getPluginForFilename = function (sceneFilename) {
  69003. if (sceneFilename.name) {
  69004. sceneFilename = sceneFilename.name;
  69005. }
  69006. var queryStringPosition = sceneFilename.indexOf("?");
  69007. if (queryStringPosition !== -1) {
  69008. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  69009. }
  69010. var dotPosition = sceneFilename.lastIndexOf(".");
  69011. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  69012. return SceneLoader._getPluginForExtension(extension);
  69013. };
  69014. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  69015. SceneLoader._getDirectLoad = function (sceneFilename) {
  69016. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  69017. return sceneFilename.substr(5);
  69018. }
  69019. return null;
  69020. };
  69021. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  69022. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  69023. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  69024. var plugin;
  69025. if (registeredPlugin.plugin.createPlugin) {
  69026. plugin = registeredPlugin.plugin.createPlugin();
  69027. }
  69028. else {
  69029. plugin = registeredPlugin.plugin;
  69030. }
  69031. var useArrayBuffer = registeredPlugin.isBinary;
  69032. var database;
  69033. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  69034. var dataCallback = function (data, responseURL) {
  69035. if (scene.isDisposed) {
  69036. onError("Scene has been disposed");
  69037. return;
  69038. }
  69039. scene.database = database;
  69040. onSuccess(plugin, data, responseURL);
  69041. };
  69042. var request = null;
  69043. var pluginDisposed = false;
  69044. var onDisposeObservable = plugin.onDisposeObservable;
  69045. if (onDisposeObservable) {
  69046. onDisposeObservable.add(function () {
  69047. pluginDisposed = true;
  69048. if (request) {
  69049. request.abort();
  69050. request = null;
  69051. }
  69052. onDispose();
  69053. });
  69054. }
  69055. var manifestChecked = function () {
  69056. if (pluginDisposed) {
  69057. return;
  69058. }
  69059. var url = rootUrl + sceneFilename;
  69060. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  69061. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  69062. } : undefined, database, useArrayBuffer, function (request, exception) {
  69063. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  69064. });
  69065. };
  69066. if (directLoad) {
  69067. dataCallback(directLoad);
  69068. return plugin;
  69069. }
  69070. if (rootUrl.indexOf("file:") === -1) {
  69071. var engine = scene.getEngine();
  69072. var canUseOfflineSupport = engine.enableOfflineSupport;
  69073. if (canUseOfflineSupport) {
  69074. // Also check for exceptions
  69075. var exceptionFound = false;
  69076. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  69077. var regex = _a[_i];
  69078. if (regex.test(rootUrl + sceneFilename)) {
  69079. exceptionFound = true;
  69080. break;
  69081. }
  69082. }
  69083. canUseOfflineSupport = !exceptionFound;
  69084. }
  69085. if (canUseOfflineSupport) {
  69086. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  69087. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  69088. }
  69089. else {
  69090. manifestChecked();
  69091. }
  69092. }
  69093. // Loading file from disk via input file or drag'n'drop
  69094. else {
  69095. var fileOrString = sceneFilename;
  69096. if (fileOrString.name) { // File
  69097. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  69098. }
  69099. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  69100. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  69101. }
  69102. else {
  69103. onError("Unable to find file named " + sceneFilename);
  69104. }
  69105. }
  69106. return plugin;
  69107. };
  69108. // Public functions
  69109. SceneLoader.GetPluginForExtension = function (extension) {
  69110. return SceneLoader._getPluginForExtension(extension).plugin;
  69111. };
  69112. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  69113. return !!SceneLoader._registeredPlugins[extension];
  69114. };
  69115. SceneLoader.RegisterPlugin = function (plugin) {
  69116. if (typeof plugin.extensions === "string") {
  69117. var extension = plugin.extensions;
  69118. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69119. plugin: plugin,
  69120. isBinary: false
  69121. };
  69122. }
  69123. else {
  69124. var extensions = plugin.extensions;
  69125. Object.keys(extensions).forEach(function (extension) {
  69126. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69127. plugin: plugin,
  69128. isBinary: extensions[extension].isBinary
  69129. };
  69130. });
  69131. }
  69132. };
  69133. /**
  69134. * Import meshes into a scene
  69135. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69136. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69137. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69138. * @param scene the instance of BABYLON.Scene to append to
  69139. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  69140. * @param onProgress a callback with a progress event for each file being loaded
  69141. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69142. * @param pluginExtension the extension used to determine the plugin
  69143. * @returns The loaded plugin
  69144. */
  69145. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69146. if (sceneFilename === void 0) { sceneFilename = ""; }
  69147. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69148. if (onSuccess === void 0) { onSuccess = null; }
  69149. if (onProgress === void 0) { onProgress = null; }
  69150. if (onError === void 0) { onError = null; }
  69151. if (pluginExtension === void 0) { pluginExtension = null; }
  69152. if (!scene) {
  69153. BABYLON.Tools.Error("No scene available to import mesh to");
  69154. return null;
  69155. }
  69156. if (!sceneFilename) {
  69157. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69158. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69159. }
  69160. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69161. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69162. return null;
  69163. }
  69164. var loadingToken = {};
  69165. scene._addPendingData(loadingToken);
  69166. var disposeHandler = function () {
  69167. scene._removePendingData(loadingToken);
  69168. };
  69169. var errorHandler = function (message, exception) {
  69170. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  69171. if (onError) {
  69172. onError(scene, errorMessage, exception);
  69173. }
  69174. else {
  69175. BABYLON.Tools.Error(errorMessage);
  69176. // should the exception be thrown?
  69177. }
  69178. disposeHandler();
  69179. };
  69180. var progressHandler = onProgress ? function (event) {
  69181. try {
  69182. onProgress(event);
  69183. }
  69184. catch (e) {
  69185. errorHandler("Error in onProgress callback", e);
  69186. }
  69187. } : undefined;
  69188. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  69189. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  69190. if (onSuccess) {
  69191. try {
  69192. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  69193. }
  69194. catch (e) {
  69195. errorHandler("Error in onSuccess callback", e);
  69196. }
  69197. }
  69198. scene._removePendingData(loadingToken);
  69199. };
  69200. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69201. if (plugin.rewriteRootURL) {
  69202. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  69203. }
  69204. if (sceneFilename === "") {
  69205. if (sceneFilename === "") {
  69206. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69207. }
  69208. }
  69209. if (plugin.importMesh) {
  69210. var syncedPlugin = plugin;
  69211. var meshes = new Array();
  69212. var particleSystems = new Array();
  69213. var skeletons = new Array();
  69214. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  69215. return;
  69216. }
  69217. scene.loadingPluginName = plugin.name;
  69218. successHandler(meshes, particleSystems, skeletons, []);
  69219. }
  69220. else {
  69221. var asyncedPlugin = plugin;
  69222. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  69223. scene.loadingPluginName = plugin.name;
  69224. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  69225. }).catch(function (error) {
  69226. errorHandler(error.message, error);
  69227. });
  69228. }
  69229. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69230. };
  69231. /**
  69232. * Import meshes into a scene
  69233. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69234. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69235. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69236. * @param scene the instance of BABYLON.Scene to append to
  69237. * @param onProgress a callback with a progress event for each file being loaded
  69238. * @param pluginExtension the extension used to determine the plugin
  69239. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  69240. */
  69241. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69242. if (sceneFilename === void 0) { sceneFilename = ""; }
  69243. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69244. if (onProgress === void 0) { onProgress = null; }
  69245. if (pluginExtension === void 0) { pluginExtension = null; }
  69246. return new Promise(function (resolve, reject) {
  69247. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  69248. resolve({
  69249. meshes: meshes,
  69250. particleSystems: particleSystems,
  69251. skeletons: skeletons,
  69252. animationGroups: animationGroups
  69253. });
  69254. }, onProgress, function (scene, message, exception) {
  69255. reject(exception || new Error(message));
  69256. }, pluginExtension);
  69257. });
  69258. };
  69259. /**
  69260. * Load a scene
  69261. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69262. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69263. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69264. * @param onSuccess a callback with the scene when import succeeds
  69265. * @param onProgress a callback with a progress event for each file being loaded
  69266. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69267. * @param pluginExtension the extension used to determine the plugin
  69268. * @returns The loaded plugin
  69269. */
  69270. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  69271. if (onSuccess === void 0) { onSuccess = null; }
  69272. if (onProgress === void 0) { onProgress = null; }
  69273. if (onError === void 0) { onError = null; }
  69274. if (pluginExtension === void 0) { pluginExtension = null; }
  69275. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  69276. };
  69277. /**
  69278. * Load a scene
  69279. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69280. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69281. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69282. * @param onProgress a callback with a progress event for each file being loaded
  69283. * @param pluginExtension the extension used to determine the plugin
  69284. * @returns The loaded scene
  69285. */
  69286. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  69287. if (onProgress === void 0) { onProgress = null; }
  69288. if (pluginExtension === void 0) { pluginExtension = null; }
  69289. return new Promise(function (resolve, reject) {
  69290. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  69291. resolve(scene);
  69292. }, onProgress, function (scene, message, exception) {
  69293. reject(exception || new Error(message));
  69294. }, pluginExtension);
  69295. });
  69296. };
  69297. /**
  69298. * Append a scene
  69299. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69300. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69301. * @param scene is the instance of BABYLON.Scene to append to
  69302. * @param onSuccess a callback with the scene when import succeeds
  69303. * @param onProgress a callback with a progress event for each file being loaded
  69304. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69305. * @param pluginExtension the extension used to determine the plugin
  69306. * @returns The loaded plugin
  69307. */
  69308. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69309. if (sceneFilename === void 0) { sceneFilename = ""; }
  69310. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69311. if (onSuccess === void 0) { onSuccess = null; }
  69312. if (onProgress === void 0) { onProgress = null; }
  69313. if (onError === void 0) { onError = null; }
  69314. if (pluginExtension === void 0) { pluginExtension = null; }
  69315. if (!scene) {
  69316. BABYLON.Tools.Error("No scene available to append to");
  69317. return null;
  69318. }
  69319. if (!sceneFilename) {
  69320. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69321. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69322. }
  69323. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69324. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69325. return null;
  69326. }
  69327. if (SceneLoader.ShowLoadingScreen) {
  69328. scene.getEngine().displayLoadingUI();
  69329. }
  69330. var loadingToken = {};
  69331. scene._addPendingData(loadingToken);
  69332. var disposeHandler = function () {
  69333. scene._removePendingData(loadingToken);
  69334. scene.getEngine().hideLoadingUI();
  69335. };
  69336. var errorHandler = function (message, exception) {
  69337. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69338. if (onError) {
  69339. onError(scene, errorMessage, exception);
  69340. }
  69341. else {
  69342. BABYLON.Tools.Error(errorMessage);
  69343. // should the exception be thrown?
  69344. }
  69345. disposeHandler();
  69346. };
  69347. var progressHandler = onProgress ? function (event) {
  69348. try {
  69349. onProgress(event);
  69350. }
  69351. catch (e) {
  69352. errorHandler("Error in onProgress callback", e);
  69353. }
  69354. } : undefined;
  69355. var successHandler = function () {
  69356. if (onSuccess) {
  69357. try {
  69358. onSuccess(scene);
  69359. }
  69360. catch (e) {
  69361. errorHandler("Error in onSuccess callback", e);
  69362. }
  69363. }
  69364. scene._removePendingData(loadingToken);
  69365. };
  69366. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69367. if (sceneFilename === "") {
  69368. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69369. }
  69370. if (plugin.load) {
  69371. var syncedPlugin = plugin;
  69372. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  69373. return;
  69374. }
  69375. scene.loadingPluginName = plugin.name;
  69376. successHandler();
  69377. }
  69378. else {
  69379. var asyncedPlugin = plugin;
  69380. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  69381. scene.loadingPluginName = plugin.name;
  69382. successHandler();
  69383. }).catch(function (error) {
  69384. errorHandler(error.message, error);
  69385. });
  69386. }
  69387. if (SceneLoader.ShowLoadingScreen) {
  69388. scene.executeWhenReady(function () {
  69389. scene.getEngine().hideLoadingUI();
  69390. });
  69391. }
  69392. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69393. };
  69394. /**
  69395. * Append a scene
  69396. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69397. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69398. * @param scene is the instance of BABYLON.Scene to append to
  69399. * @param onProgress a callback with a progress event for each file being loaded
  69400. * @param pluginExtension the extension used to determine the plugin
  69401. * @returns The given scene
  69402. */
  69403. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69404. if (sceneFilename === void 0) { sceneFilename = ""; }
  69405. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69406. if (onProgress === void 0) { onProgress = null; }
  69407. if (pluginExtension === void 0) { pluginExtension = null; }
  69408. return new Promise(function (resolve, reject) {
  69409. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  69410. resolve(scene);
  69411. }, onProgress, function (scene, message, exception) {
  69412. reject(exception || new Error(message));
  69413. }, pluginExtension);
  69414. });
  69415. };
  69416. /**
  69417. * Load a scene into an asset container
  69418. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69419. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69420. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  69421. * @param onSuccess a callback with the scene when import succeeds
  69422. * @param onProgress a callback with a progress event for each file being loaded
  69423. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69424. * @param pluginExtension the extension used to determine the plugin
  69425. * @returns The loaded plugin
  69426. */
  69427. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69428. if (sceneFilename === void 0) { sceneFilename = ""; }
  69429. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69430. if (onSuccess === void 0) { onSuccess = null; }
  69431. if (onProgress === void 0) { onProgress = null; }
  69432. if (onError === void 0) { onError = null; }
  69433. if (pluginExtension === void 0) { pluginExtension = null; }
  69434. if (!scene) {
  69435. BABYLON.Tools.Error("No scene available to load asset container to");
  69436. return null;
  69437. }
  69438. if (!sceneFilename) {
  69439. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69440. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69441. }
  69442. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69443. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69444. return null;
  69445. }
  69446. var loadingToken = {};
  69447. scene._addPendingData(loadingToken);
  69448. var disposeHandler = function () {
  69449. scene._removePendingData(loadingToken);
  69450. };
  69451. var errorHandler = function (message, exception) {
  69452. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69453. if (onError) {
  69454. onError(scene, errorMessage, exception);
  69455. }
  69456. else {
  69457. BABYLON.Tools.Error(errorMessage);
  69458. // should the exception be thrown?
  69459. }
  69460. disposeHandler();
  69461. };
  69462. var progressHandler = onProgress ? function (event) {
  69463. try {
  69464. onProgress(event);
  69465. }
  69466. catch (e) {
  69467. errorHandler("Error in onProgress callback", e);
  69468. }
  69469. } : undefined;
  69470. var successHandler = function (assets) {
  69471. if (onSuccess) {
  69472. try {
  69473. onSuccess(assets);
  69474. }
  69475. catch (e) {
  69476. errorHandler("Error in onSuccess callback", e);
  69477. }
  69478. }
  69479. scene._removePendingData(loadingToken);
  69480. };
  69481. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69482. if (plugin.loadAssetContainer) {
  69483. var syncedPlugin = plugin;
  69484. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  69485. if (!assetContainer) {
  69486. return;
  69487. }
  69488. scene.loadingPluginName = plugin.name;
  69489. successHandler(assetContainer);
  69490. }
  69491. else if (plugin.loadAssetContainerAsync) {
  69492. var asyncedPlugin = plugin;
  69493. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  69494. scene.loadingPluginName = plugin.name;
  69495. successHandler(assetContainer);
  69496. }).catch(function (error) {
  69497. errorHandler(error.message, error);
  69498. });
  69499. }
  69500. else {
  69501. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  69502. }
  69503. if (SceneLoader.ShowLoadingScreen) {
  69504. scene.executeWhenReady(function () {
  69505. scene.getEngine().hideLoadingUI();
  69506. });
  69507. }
  69508. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69509. };
  69510. /**
  69511. * Load a scene into an asset container
  69512. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69513. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69514. * @param scene is the instance of BABYLON.Scene to append to
  69515. * @param onProgress a callback with a progress event for each file being loaded
  69516. * @param pluginExtension the extension used to determine the plugin
  69517. * @returns The loaded asset container
  69518. */
  69519. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69520. if (sceneFilename === void 0) { sceneFilename = ""; }
  69521. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69522. if (onProgress === void 0) { onProgress = null; }
  69523. if (pluginExtension === void 0) { pluginExtension = null; }
  69524. return new Promise(function (resolve, reject) {
  69525. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  69526. resolve(assetContainer);
  69527. }, onProgress, function (scene, message, exception) {
  69528. reject(exception || new Error(message));
  69529. }, pluginExtension);
  69530. });
  69531. };
  69532. // Flags
  69533. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  69534. SceneLoader._ShowLoadingScreen = true;
  69535. SceneLoader._CleanBoneMatrixWeights = false;
  69536. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  69537. // Members
  69538. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  69539. SceneLoader._registeredPlugins = {};
  69540. return SceneLoader;
  69541. }());
  69542. BABYLON.SceneLoader = SceneLoader;
  69543. ;
  69544. })(BABYLON || (BABYLON = {}));
  69545. //# sourceMappingURL=babylon.sceneLoader.js.map
  69546. var BABYLON;
  69547. (function (BABYLON) {
  69548. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  69549. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69550. var parsedMaterial = parsedData.materials[index];
  69551. if (parsedMaterial.id === id) {
  69552. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69553. }
  69554. }
  69555. return null;
  69556. };
  69557. var isDescendantOf = function (mesh, names, hierarchyIds) {
  69558. for (var i in names) {
  69559. if (mesh.name === names[i]) {
  69560. hierarchyIds.push(mesh.id);
  69561. return true;
  69562. }
  69563. }
  69564. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  69565. hierarchyIds.push(mesh.id);
  69566. return true;
  69567. }
  69568. return false;
  69569. };
  69570. var logOperation = function (operation, producer) {
  69571. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  69572. };
  69573. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  69574. if (addToScene === void 0) { addToScene = false; }
  69575. var container = new BABYLON.AssetContainer(scene);
  69576. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69577. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69578. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69579. // and avoid problems with multiple concurrent .babylon loads.
  69580. var log = "importScene has failed JSON parse";
  69581. try {
  69582. var parsedData = JSON.parse(data);
  69583. log = "";
  69584. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69585. var index;
  69586. var cache;
  69587. // Lights
  69588. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  69589. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  69590. var parsedLight = parsedData.lights[index];
  69591. var light = BABYLON.Light.Parse(parsedLight, scene);
  69592. if (light) {
  69593. container.lights.push(light);
  69594. log += (index === 0 ? "\n\tLights:" : "");
  69595. log += "\n\t\t" + light.toString(fullDetails);
  69596. }
  69597. }
  69598. }
  69599. // Animations
  69600. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  69601. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  69602. var parsedAnimation = parsedData.animations[index];
  69603. var animation = BABYLON.Animation.Parse(parsedAnimation);
  69604. scene.animations.push(animation);
  69605. container.animations.push(animation);
  69606. log += (index === 0 ? "\n\tAnimations:" : "");
  69607. log += "\n\t\t" + animation.toString(fullDetails);
  69608. }
  69609. }
  69610. // Materials
  69611. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  69612. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69613. var parsedMaterial = parsedData.materials[index];
  69614. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69615. container.materials.push(mat);
  69616. log += (index === 0 ? "\n\tMaterials:" : "");
  69617. log += "\n\t\t" + mat.toString(fullDetails);
  69618. }
  69619. }
  69620. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69621. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  69622. var parsedMultiMaterial = parsedData.multiMaterials[index];
  69623. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69624. container.multiMaterials.push(mmat);
  69625. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  69626. log += "\n\t\t" + mmat.toString(fullDetails);
  69627. }
  69628. }
  69629. // Morph targets
  69630. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69631. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69632. var managerData = _a[_i];
  69633. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  69634. }
  69635. }
  69636. // Skeletons
  69637. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69638. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  69639. var parsedSkeleton = parsedData.skeletons[index];
  69640. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69641. container.skeletons.push(skeleton);
  69642. log += (index === 0 ? "\n\tSkeletons:" : "");
  69643. log += "\n\t\t" + skeleton.toString(fullDetails);
  69644. }
  69645. }
  69646. // Geometries
  69647. var geometries = parsedData.geometries;
  69648. if (geometries !== undefined && geometries !== null) {
  69649. var addedGeometry = new Array();
  69650. // Boxes
  69651. var boxes = geometries.boxes;
  69652. if (boxes !== undefined && boxes !== null) {
  69653. for (index = 0, cache = boxes.length; index < cache; index++) {
  69654. var parsedBox = boxes[index];
  69655. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  69656. }
  69657. }
  69658. // Spheres
  69659. var spheres = geometries.spheres;
  69660. if (spheres !== undefined && spheres !== null) {
  69661. for (index = 0, cache = spheres.length; index < cache; index++) {
  69662. var parsedSphere = spheres[index];
  69663. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  69664. }
  69665. }
  69666. // Cylinders
  69667. var cylinders = geometries.cylinders;
  69668. if (cylinders !== undefined && cylinders !== null) {
  69669. for (index = 0, cache = cylinders.length; index < cache; index++) {
  69670. var parsedCylinder = cylinders[index];
  69671. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  69672. }
  69673. }
  69674. // Toruses
  69675. var toruses = geometries.toruses;
  69676. if (toruses !== undefined && toruses !== null) {
  69677. for (index = 0, cache = toruses.length; index < cache; index++) {
  69678. var parsedTorus = toruses[index];
  69679. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  69680. }
  69681. }
  69682. // Grounds
  69683. var grounds = geometries.grounds;
  69684. if (grounds !== undefined && grounds !== null) {
  69685. for (index = 0, cache = grounds.length; index < cache; index++) {
  69686. var parsedGround = grounds[index];
  69687. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  69688. }
  69689. }
  69690. // Planes
  69691. var planes = geometries.planes;
  69692. if (planes !== undefined && planes !== null) {
  69693. for (index = 0, cache = planes.length; index < cache; index++) {
  69694. var parsedPlane = planes[index];
  69695. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  69696. }
  69697. }
  69698. // TorusKnots
  69699. var torusKnots = geometries.torusKnots;
  69700. if (torusKnots !== undefined && torusKnots !== null) {
  69701. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  69702. var parsedTorusKnot = torusKnots[index];
  69703. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  69704. }
  69705. }
  69706. // VertexData
  69707. var vertexData = geometries.vertexData;
  69708. if (vertexData !== undefined && vertexData !== null) {
  69709. for (index = 0, cache = vertexData.length; index < cache; index++) {
  69710. var parsedVertexData = vertexData[index];
  69711. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  69712. }
  69713. }
  69714. addedGeometry.forEach(function (g) {
  69715. if (g) {
  69716. container.geometries.push(g);
  69717. }
  69718. });
  69719. }
  69720. // Transform nodes
  69721. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  69722. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  69723. var parsedTransformNode = parsedData.transformNodes[index];
  69724. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  69725. container.transformNodes.push(node);
  69726. }
  69727. }
  69728. // Meshes
  69729. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69730. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69731. var parsedMesh = parsedData.meshes[index];
  69732. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69733. container.meshes.push(mesh);
  69734. log += (index === 0 ? "\n\tMeshes:" : "");
  69735. log += "\n\t\t" + mesh.toString(fullDetails);
  69736. }
  69737. }
  69738. // Cameras
  69739. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  69740. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  69741. var parsedCamera = parsedData.cameras[index];
  69742. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  69743. container.cameras.push(camera);
  69744. log += (index === 0 ? "\n\tCameras:" : "");
  69745. log += "\n\t\t" + camera.toString(fullDetails);
  69746. }
  69747. }
  69748. // Browsing all the graph to connect the dots
  69749. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  69750. var camera = scene.cameras[index];
  69751. if (camera._waitingParentId) {
  69752. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  69753. camera._waitingParentId = null;
  69754. }
  69755. }
  69756. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69757. var light_1 = scene.lights[index];
  69758. if (light_1 && light_1._waitingParentId) {
  69759. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  69760. light_1._waitingParentId = null;
  69761. }
  69762. }
  69763. // Sounds
  69764. // TODO: add sound
  69765. var loadedSounds = [];
  69766. var loadedSound;
  69767. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69768. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69769. var parsedSound = parsedData.sounds[index];
  69770. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69771. if (!parsedSound.url)
  69772. parsedSound.url = parsedSound.name;
  69773. if (!loadedSounds[parsedSound.url]) {
  69774. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69775. loadedSounds[parsedSound.url] = loadedSound;
  69776. container.sounds.push(loadedSound);
  69777. }
  69778. else {
  69779. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69780. }
  69781. }
  69782. else {
  69783. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69784. }
  69785. }
  69786. }
  69787. loadedSounds = [];
  69788. // Connect parents & children and parse actions
  69789. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  69790. var transformNode = scene.transformNodes[index];
  69791. if (transformNode._waitingParentId) {
  69792. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  69793. transformNode._waitingParentId = null;
  69794. }
  69795. }
  69796. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69797. var mesh = scene.meshes[index];
  69798. if (mesh._waitingParentId) {
  69799. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  69800. mesh._waitingParentId = null;
  69801. }
  69802. if (mesh._waitingActions) {
  69803. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  69804. mesh._waitingActions = null;
  69805. }
  69806. }
  69807. // freeze world matrix application
  69808. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69809. var currentMesh = scene.meshes[index];
  69810. if (currentMesh._waitingFreezeWorldMatrix) {
  69811. currentMesh.freezeWorldMatrix();
  69812. currentMesh._waitingFreezeWorldMatrix = null;
  69813. }
  69814. else {
  69815. currentMesh.computeWorldMatrix(true);
  69816. }
  69817. }
  69818. // Shadows
  69819. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  69820. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  69821. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  69822. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  69823. // SG would be available on their associated lights
  69824. }
  69825. }
  69826. // Lights exclusions / inclusions
  69827. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69828. var light_2 = scene.lights[index];
  69829. // Excluded check
  69830. if (light_2._excludedMeshesIds.length > 0) {
  69831. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  69832. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  69833. if (excludedMesh) {
  69834. light_2.excludedMeshes.push(excludedMesh);
  69835. }
  69836. }
  69837. light_2._excludedMeshesIds = [];
  69838. }
  69839. // Included check
  69840. if (light_2._includedOnlyMeshesIds.length > 0) {
  69841. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  69842. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  69843. if (includedOnlyMesh) {
  69844. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  69845. }
  69846. }
  69847. light_2._includedOnlyMeshesIds = [];
  69848. }
  69849. }
  69850. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  69851. // Actions (scene)
  69852. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  69853. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  69854. }
  69855. if (!addToScene) {
  69856. container.removeAllFromScene();
  69857. }
  69858. }
  69859. catch (err) {
  69860. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  69861. if (onError) {
  69862. onError(msg, err);
  69863. }
  69864. else {
  69865. BABYLON.Tools.Log(msg);
  69866. throw err;
  69867. }
  69868. }
  69869. finally {
  69870. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69871. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69872. }
  69873. }
  69874. return container;
  69875. };
  69876. BABYLON.SceneLoader.RegisterPlugin({
  69877. name: "babylon.js",
  69878. extensions: ".babylon",
  69879. canDirectLoad: function (data) {
  69880. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  69881. return true;
  69882. }
  69883. return false;
  69884. },
  69885. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  69886. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69887. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69888. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69889. // and avoid problems with multiple concurrent .babylon loads.
  69890. var log = "importMesh has failed JSON parse";
  69891. try {
  69892. var parsedData = JSON.parse(data);
  69893. log = "";
  69894. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69895. if (!meshesNames) {
  69896. meshesNames = null;
  69897. }
  69898. else if (!Array.isArray(meshesNames)) {
  69899. meshesNames = [meshesNames];
  69900. }
  69901. var hierarchyIds = new Array();
  69902. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69903. var loadedSkeletonsIds = [];
  69904. var loadedMaterialsIds = [];
  69905. var index;
  69906. var cache;
  69907. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69908. var parsedMesh = parsedData.meshes[index];
  69909. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  69910. if (meshesNames !== null) {
  69911. // Remove found mesh name from list.
  69912. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  69913. }
  69914. //Geometry?
  69915. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  69916. //does the file contain geometries?
  69917. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  69918. //find the correct geometry and add it to the scene
  69919. var found = false;
  69920. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  69921. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  69922. return;
  69923. }
  69924. else {
  69925. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  69926. if (parsedGeometryData.id === parsedMesh.geometryId) {
  69927. switch (geometryType) {
  69928. case "boxes":
  69929. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  69930. break;
  69931. case "spheres":
  69932. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  69933. break;
  69934. case "cylinders":
  69935. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  69936. break;
  69937. case "toruses":
  69938. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  69939. break;
  69940. case "grounds":
  69941. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  69942. break;
  69943. case "planes":
  69944. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  69945. break;
  69946. case "torusKnots":
  69947. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  69948. break;
  69949. case "vertexData":
  69950. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  69951. break;
  69952. }
  69953. found = true;
  69954. }
  69955. });
  69956. }
  69957. });
  69958. if (found === false) {
  69959. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  69960. }
  69961. }
  69962. }
  69963. // Material ?
  69964. if (parsedMesh.materialId) {
  69965. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  69966. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69967. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  69968. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  69969. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  69970. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  69971. var subMatId = parsedMultiMaterial.materials[matIndex];
  69972. loadedMaterialsIds.push(subMatId);
  69973. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  69974. if (mat) {
  69975. log += "\n\tMaterial " + mat.toString(fullDetails);
  69976. }
  69977. }
  69978. loadedMaterialsIds.push(parsedMultiMaterial.id);
  69979. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69980. if (mmat) {
  69981. materialFound = true;
  69982. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  69983. }
  69984. break;
  69985. }
  69986. }
  69987. }
  69988. if (materialFound === false) {
  69989. loadedMaterialsIds.push(parsedMesh.materialId);
  69990. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  69991. if (!mat) {
  69992. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  69993. }
  69994. else {
  69995. log += "\n\tMaterial " + mat.toString(fullDetails);
  69996. }
  69997. }
  69998. }
  69999. // Skeleton ?
  70000. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70001. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  70002. if (skeletonAlreadyLoaded === false) {
  70003. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  70004. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  70005. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  70006. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70007. skeletons.push(skeleton);
  70008. loadedSkeletonsIds.push(parsedSkeleton.id);
  70009. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  70010. }
  70011. }
  70012. }
  70013. }
  70014. // Morph targets ?
  70015. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70016. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70017. var managerData = _a[_i];
  70018. BABYLON.MorphTargetManager.Parse(managerData, scene);
  70019. }
  70020. }
  70021. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70022. meshes.push(mesh);
  70023. log += "\n\tMesh " + mesh.toString(fullDetails);
  70024. }
  70025. }
  70026. // Connecting parents
  70027. var currentMesh;
  70028. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70029. currentMesh = scene.meshes[index];
  70030. if (currentMesh._waitingParentId) {
  70031. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  70032. currentMesh._waitingParentId = null;
  70033. }
  70034. }
  70035. // freeze and compute world matrix application
  70036. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70037. currentMesh = scene.meshes[index];
  70038. if (currentMesh._waitingFreezeWorldMatrix) {
  70039. currentMesh.freezeWorldMatrix();
  70040. currentMesh._waitingFreezeWorldMatrix = null;
  70041. }
  70042. else {
  70043. currentMesh.computeWorldMatrix(true);
  70044. }
  70045. }
  70046. }
  70047. // Particles
  70048. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  70049. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  70050. if (parser) {
  70051. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  70052. var parsedParticleSystem = parsedData.particleSystems[index];
  70053. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  70054. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  70055. }
  70056. }
  70057. }
  70058. }
  70059. return true;
  70060. }
  70061. catch (err) {
  70062. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  70063. if (onError) {
  70064. onError(msg, err);
  70065. }
  70066. else {
  70067. BABYLON.Tools.Log(msg);
  70068. throw err;
  70069. }
  70070. }
  70071. finally {
  70072. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70073. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70074. }
  70075. }
  70076. return false;
  70077. },
  70078. load: function (scene, data, rootUrl, onError) {
  70079. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70080. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70081. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70082. // and avoid problems with multiple concurrent .babylon loads.
  70083. var log = "importScene has failed JSON parse";
  70084. try {
  70085. var parsedData = JSON.parse(data);
  70086. log = "";
  70087. // Scene
  70088. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  70089. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  70090. }
  70091. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  70092. scene.autoClear = parsedData.autoClear;
  70093. }
  70094. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  70095. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  70096. }
  70097. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  70098. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  70099. }
  70100. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  70101. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  70102. }
  70103. // Fog
  70104. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  70105. scene.fogMode = parsedData.fogMode;
  70106. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  70107. scene.fogStart = parsedData.fogStart;
  70108. scene.fogEnd = parsedData.fogEnd;
  70109. scene.fogDensity = parsedData.fogDensity;
  70110. log += "\tFog mode for scene: ";
  70111. switch (scene.fogMode) {
  70112. // getters not compiling, so using hardcoded
  70113. case 1:
  70114. log += "exp\n";
  70115. break;
  70116. case 2:
  70117. log += "exp2\n";
  70118. break;
  70119. case 3:
  70120. log += "linear\n";
  70121. break;
  70122. }
  70123. }
  70124. //Physics
  70125. if (parsedData.physicsEnabled) {
  70126. var physicsPlugin;
  70127. if (parsedData.physicsEngine === "cannon") {
  70128. physicsPlugin = new BABYLON.CannonJSPlugin();
  70129. }
  70130. else if (parsedData.physicsEngine === "oimo") {
  70131. physicsPlugin = new BABYLON.OimoJSPlugin();
  70132. }
  70133. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  70134. //else - default engine, which is currently oimo
  70135. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  70136. scene.enablePhysics(physicsGravity, physicsPlugin);
  70137. }
  70138. // Metadata
  70139. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  70140. scene.metadata = parsedData.metadata;
  70141. }
  70142. //collisions, if defined. otherwise, default is true
  70143. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  70144. scene.collisionsEnabled = parsedData.collisionsEnabled;
  70145. }
  70146. scene.workerCollisions = !!parsedData.workerCollisions;
  70147. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  70148. if (!container) {
  70149. return false;
  70150. }
  70151. if (parsedData.autoAnimate) {
  70152. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  70153. }
  70154. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  70155. scene.setActiveCameraByID(parsedData.activeCameraID);
  70156. }
  70157. // Environment texture
  70158. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  70159. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  70160. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  70161. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  70162. if (parsedData.environmentTextureRotationY) {
  70163. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  70164. }
  70165. scene.environmentTexture = hdrTexture;
  70166. }
  70167. else {
  70168. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  70169. if (parsedData.environmentTextureRotationY) {
  70170. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  70171. }
  70172. scene.environmentTexture = cubeTexture;
  70173. }
  70174. if (parsedData.createDefaultSkybox === true) {
  70175. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  70176. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  70177. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  70178. }
  70179. }
  70180. // Finish
  70181. return true;
  70182. }
  70183. catch (err) {
  70184. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  70185. if (onError) {
  70186. onError(msg, err);
  70187. }
  70188. else {
  70189. BABYLON.Tools.Log(msg);
  70190. throw err;
  70191. }
  70192. }
  70193. finally {
  70194. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70195. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70196. }
  70197. }
  70198. return false;
  70199. },
  70200. loadAssetContainer: function (scene, data, rootUrl, onError) {
  70201. var container = loadAssetContainer(scene, data, rootUrl, onError);
  70202. return container;
  70203. }
  70204. });
  70205. })(BABYLON || (BABYLON = {}));
  70206. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  70207. var BABYLON;
  70208. (function (BABYLON) {
  70209. var FilesInput = /** @class */ (function () {
  70210. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  70211. this.onProcessFileCallback = function () { return true; };
  70212. this._engine = engine;
  70213. this._currentScene = scene;
  70214. this._sceneLoadedCallback = sceneLoadedCallback;
  70215. this._progressCallback = progressCallback;
  70216. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  70217. this._textureLoadingCallback = textureLoadingCallback;
  70218. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  70219. this._onReloadCallback = onReloadCallback;
  70220. this._errorCallback = errorCallback;
  70221. }
  70222. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  70223. var _this = this;
  70224. if (elementToMonitor) {
  70225. this._elementToMonitor = elementToMonitor;
  70226. this._dragEnterHandler = function (e) { _this.drag(e); };
  70227. this._dragOverHandler = function (e) { _this.drag(e); };
  70228. this._dropHandler = function (e) { _this.drop(e); };
  70229. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  70230. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  70231. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  70232. }
  70233. };
  70234. FilesInput.prototype.dispose = function () {
  70235. if (!this._elementToMonitor) {
  70236. return;
  70237. }
  70238. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  70239. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  70240. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  70241. };
  70242. FilesInput.prototype.renderFunction = function () {
  70243. if (this._additionalRenderLoopLogicCallback) {
  70244. this._additionalRenderLoopLogicCallback();
  70245. }
  70246. if (this._currentScene) {
  70247. if (this._textureLoadingCallback) {
  70248. var remaining = this._currentScene.getWaitingItemsCount();
  70249. if (remaining > 0) {
  70250. this._textureLoadingCallback(remaining);
  70251. }
  70252. }
  70253. this._currentScene.render();
  70254. }
  70255. };
  70256. FilesInput.prototype.drag = function (e) {
  70257. e.stopPropagation();
  70258. e.preventDefault();
  70259. };
  70260. FilesInput.prototype.drop = function (eventDrop) {
  70261. eventDrop.stopPropagation();
  70262. eventDrop.preventDefault();
  70263. this.loadFiles(eventDrop);
  70264. };
  70265. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  70266. var _this = this;
  70267. var reader = folder.createReader();
  70268. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  70269. reader.readEntries(function (entries) {
  70270. remaining.count += entries.length;
  70271. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  70272. var entry = entries_1[_i];
  70273. if (entry.isFile) {
  70274. entry.file(function (file) {
  70275. file.correctName = relativePath + file.name;
  70276. files.push(file);
  70277. if (--remaining.count === 0) {
  70278. callback();
  70279. }
  70280. });
  70281. }
  70282. else if (entry.isDirectory) {
  70283. _this._traverseFolder(entry, files, remaining, callback);
  70284. }
  70285. }
  70286. if (--remaining.count) {
  70287. callback();
  70288. }
  70289. });
  70290. };
  70291. FilesInput.prototype._processFiles = function (files) {
  70292. for (var i = 0; i < files.length; i++) {
  70293. var name = files[i].correctName.toLowerCase();
  70294. var extension = name.split('.').pop();
  70295. if (!this.onProcessFileCallback(files[i], name, extension)) {
  70296. continue;
  70297. }
  70298. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  70299. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  70300. this._sceneFileToLoad = files[i];
  70301. }
  70302. else {
  70303. FilesInput.FilesToLoad[name] = files[i];
  70304. }
  70305. }
  70306. };
  70307. FilesInput.prototype.loadFiles = function (event) {
  70308. var _this = this;
  70309. if (this._startingProcessingFilesCallback)
  70310. this._startingProcessingFilesCallback();
  70311. // Handling data transfer via drag'n'drop
  70312. if (event && event.dataTransfer && event.dataTransfer.files) {
  70313. this._filesToLoad = event.dataTransfer.files;
  70314. }
  70315. // Handling files from input files
  70316. if (event && event.target && event.target.files) {
  70317. this._filesToLoad = event.target.files;
  70318. }
  70319. if (this._filesToLoad && this._filesToLoad.length > 0) {
  70320. var files_1 = new Array();
  70321. var folders = [];
  70322. var items = event.dataTransfer ? event.dataTransfer.items : null;
  70323. for (var i = 0; i < this._filesToLoad.length; i++) {
  70324. var fileToLoad = this._filesToLoad[i];
  70325. var name_1 = fileToLoad.name.toLowerCase();
  70326. var entry = void 0;
  70327. fileToLoad.correctName = name_1;
  70328. if (items) {
  70329. var item = items[i];
  70330. if (item.getAsEntry) {
  70331. entry = item.getAsEntry();
  70332. }
  70333. else if (item.webkitGetAsEntry) {
  70334. entry = item.webkitGetAsEntry();
  70335. }
  70336. }
  70337. if (!entry) {
  70338. files_1.push(fileToLoad);
  70339. }
  70340. else {
  70341. if (entry.isDirectory) {
  70342. folders.push(entry);
  70343. }
  70344. else {
  70345. files_1.push(fileToLoad);
  70346. }
  70347. }
  70348. }
  70349. if (folders.length === 0) {
  70350. this._processFiles(files_1);
  70351. this._processReload();
  70352. }
  70353. else {
  70354. var remaining = { count: folders.length };
  70355. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  70356. var folder = folders_1[_i];
  70357. this._traverseFolder(folder, files_1, remaining, function () {
  70358. _this._processFiles(files_1);
  70359. if (remaining.count === 0) {
  70360. _this._processReload();
  70361. }
  70362. });
  70363. }
  70364. }
  70365. }
  70366. };
  70367. FilesInput.prototype._processReload = function () {
  70368. if (this._onReloadCallback) {
  70369. this._onReloadCallback(this._sceneFileToLoad);
  70370. }
  70371. else {
  70372. this.reload();
  70373. }
  70374. };
  70375. FilesInput.prototype.reload = function () {
  70376. var _this = this;
  70377. // If a scene file has been provided
  70378. if (this._sceneFileToLoad) {
  70379. if (this._currentScene) {
  70380. if (BABYLON.Tools.errorsCount > 0) {
  70381. BABYLON.Tools.ClearLogCache();
  70382. }
  70383. this._engine.stopRenderLoop();
  70384. }
  70385. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  70386. if (_this._progressCallback) {
  70387. _this._progressCallback(progress);
  70388. }
  70389. }).then(function (scene) {
  70390. if (_this._currentScene) {
  70391. _this._currentScene.dispose();
  70392. }
  70393. _this._currentScene = scene;
  70394. if (_this._sceneLoadedCallback) {
  70395. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  70396. }
  70397. // Wait for textures and shaders to be ready
  70398. _this._currentScene.executeWhenReady(function () {
  70399. _this._engine.runRenderLoop(function () {
  70400. _this.renderFunction();
  70401. });
  70402. });
  70403. }).catch(function (error) {
  70404. if (_this._errorCallback) {
  70405. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  70406. }
  70407. });
  70408. }
  70409. else {
  70410. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  70411. }
  70412. };
  70413. FilesInput.FilesToLoad = {};
  70414. return FilesInput;
  70415. }());
  70416. BABYLON.FilesInput = FilesInput;
  70417. })(BABYLON || (BABYLON = {}));
  70418. //# sourceMappingURL=babylon.filesInput.js.map
  70419. var BABYLON;
  70420. (function (BABYLON) {
  70421. var Tags = /** @class */ (function () {
  70422. function Tags() {
  70423. }
  70424. Tags.EnableFor = function (obj) {
  70425. obj._tags = obj._tags || {};
  70426. obj.hasTags = function () {
  70427. return Tags.HasTags(obj);
  70428. };
  70429. obj.addTags = function (tagsString) {
  70430. return Tags.AddTagsTo(obj, tagsString);
  70431. };
  70432. obj.removeTags = function (tagsString) {
  70433. return Tags.RemoveTagsFrom(obj, tagsString);
  70434. };
  70435. obj.matchesTagsQuery = function (tagsQuery) {
  70436. return Tags.MatchesQuery(obj, tagsQuery);
  70437. };
  70438. };
  70439. Tags.DisableFor = function (obj) {
  70440. delete obj._tags;
  70441. delete obj.hasTags;
  70442. delete obj.addTags;
  70443. delete obj.removeTags;
  70444. delete obj.matchesTagsQuery;
  70445. };
  70446. Tags.HasTags = function (obj) {
  70447. if (!obj._tags) {
  70448. return false;
  70449. }
  70450. return !BABYLON.Tools.IsEmpty(obj._tags);
  70451. };
  70452. Tags.GetTags = function (obj, asString) {
  70453. if (asString === void 0) { asString = true; }
  70454. if (!obj._tags) {
  70455. return null;
  70456. }
  70457. if (asString) {
  70458. var tagsArray = [];
  70459. for (var tag in obj._tags) {
  70460. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  70461. tagsArray.push(tag);
  70462. }
  70463. }
  70464. return tagsArray.join(" ");
  70465. }
  70466. else {
  70467. return obj._tags;
  70468. }
  70469. };
  70470. // the tags 'true' and 'false' are reserved and cannot be used as tags
  70471. // a tag cannot start with '||', '&&', and '!'
  70472. // it cannot contain whitespaces
  70473. Tags.AddTagsTo = function (obj, tagsString) {
  70474. if (!tagsString) {
  70475. return;
  70476. }
  70477. if (typeof tagsString !== "string") {
  70478. return;
  70479. }
  70480. var tags = tagsString.split(" ");
  70481. tags.forEach(function (tag, index, array) {
  70482. Tags._AddTagTo(obj, tag);
  70483. });
  70484. };
  70485. Tags._AddTagTo = function (obj, tag) {
  70486. tag = tag.trim();
  70487. if (tag === "" || tag === "true" || tag === "false") {
  70488. return;
  70489. }
  70490. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  70491. return;
  70492. }
  70493. Tags.EnableFor(obj);
  70494. obj._tags[tag] = true;
  70495. };
  70496. Tags.RemoveTagsFrom = function (obj, tagsString) {
  70497. if (!Tags.HasTags(obj)) {
  70498. return;
  70499. }
  70500. var tags = tagsString.split(" ");
  70501. for (var t in tags) {
  70502. Tags._RemoveTagFrom(obj, tags[t]);
  70503. }
  70504. };
  70505. Tags._RemoveTagFrom = function (obj, tag) {
  70506. delete obj._tags[tag];
  70507. };
  70508. Tags.MatchesQuery = function (obj, tagsQuery) {
  70509. if (tagsQuery === undefined) {
  70510. return true;
  70511. }
  70512. if (tagsQuery === "") {
  70513. return Tags.HasTags(obj);
  70514. }
  70515. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  70516. };
  70517. return Tags;
  70518. }());
  70519. BABYLON.Tags = Tags;
  70520. })(BABYLON || (BABYLON = {}));
  70521. //# sourceMappingURL=babylon.tags.js.map
  70522. var BABYLON;
  70523. (function (BABYLON) {
  70524. /**
  70525. * Class used to evalaute queries containing `and` and `or` operators
  70526. */
  70527. var AndOrNotEvaluator = /** @class */ (function () {
  70528. function AndOrNotEvaluator() {
  70529. }
  70530. /**
  70531. * Evaluate a query
  70532. * @param query defines the query to evaluate
  70533. * @param evaluateCallback defines the callback used to filter result
  70534. * @returns true if the query matches
  70535. */
  70536. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  70537. if (!query.match(/\([^\(\)]*\)/g)) {
  70538. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  70539. }
  70540. else {
  70541. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  70542. // remove parenthesis
  70543. r = r.slice(1, r.length - 1);
  70544. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  70545. });
  70546. }
  70547. if (query === "true") {
  70548. return true;
  70549. }
  70550. if (query === "false") {
  70551. return false;
  70552. }
  70553. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  70554. };
  70555. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  70556. evaluateCallback = evaluateCallback || (function (r) {
  70557. return r === "true" ? true : false;
  70558. });
  70559. var result;
  70560. var or = parenthesisContent.split("||");
  70561. for (var i in or) {
  70562. if (or.hasOwnProperty(i)) {
  70563. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  70564. var and = ori.split("&&");
  70565. if (and.length > 1) {
  70566. for (var j = 0; j < and.length; ++j) {
  70567. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  70568. if (andj !== "true" && andj !== "false") {
  70569. if (andj[0] === "!") {
  70570. result = !evaluateCallback(andj.substring(1));
  70571. }
  70572. else {
  70573. result = evaluateCallback(andj);
  70574. }
  70575. }
  70576. else {
  70577. result = andj === "true" ? true : false;
  70578. }
  70579. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  70580. ori = "false";
  70581. break;
  70582. }
  70583. }
  70584. }
  70585. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  70586. result = true;
  70587. break;
  70588. }
  70589. // result equals false (or undefined)
  70590. if (ori !== "true" && ori !== "false") {
  70591. if (ori[0] === "!") {
  70592. result = !evaluateCallback(ori.substring(1));
  70593. }
  70594. else {
  70595. result = evaluateCallback(ori);
  70596. }
  70597. }
  70598. else {
  70599. result = ori === "true" ? true : false;
  70600. }
  70601. }
  70602. }
  70603. // the whole parenthesis scope is replaced by 'true' or 'false'
  70604. return result ? "true" : "false";
  70605. };
  70606. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  70607. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  70608. // remove whitespaces
  70609. r = r.replace(/[\s]/g, function () { return ""; });
  70610. return r.length % 2 ? "!" : "";
  70611. });
  70612. booleanString = booleanString.trim();
  70613. if (booleanString === "!true") {
  70614. booleanString = "false";
  70615. }
  70616. else if (booleanString === "!false") {
  70617. booleanString = "true";
  70618. }
  70619. return booleanString;
  70620. };
  70621. return AndOrNotEvaluator;
  70622. }());
  70623. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  70624. })(BABYLON || (BABYLON = {}));
  70625. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  70626. var BABYLON;
  70627. (function (BABYLON) {
  70628. /**
  70629. * Class used to enable access to IndexedDB
  70630. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  70631. */
  70632. var Database = /** @class */ (function () {
  70633. /**
  70634. * Creates a new Database
  70635. * @param urlToScene defines the url to load the scene
  70636. * @param callbackManifestChecked defines the callback to use when manifest is checked
  70637. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  70638. */
  70639. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  70640. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  70641. var _this = this;
  70642. // Handling various flavors of prefixed version of IndexedDB
  70643. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  70644. this.callbackManifestChecked = callbackManifestChecked;
  70645. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  70646. this.db = null;
  70647. this._enableSceneOffline = false;
  70648. this._enableTexturesOffline = false;
  70649. this.manifestVersionFound = 0;
  70650. this.mustUpdateRessources = false;
  70651. this.hasReachedQuota = false;
  70652. if (!Database.IDBStorageEnabled) {
  70653. this.callbackManifestChecked(true);
  70654. }
  70655. else {
  70656. if (disableManifestCheck) {
  70657. this._enableSceneOffline = true;
  70658. this._enableTexturesOffline = true;
  70659. this.manifestVersionFound = 1;
  70660. BABYLON.Tools.SetImmediate(function () {
  70661. _this.callbackManifestChecked(true);
  70662. });
  70663. }
  70664. else {
  70665. this._checkManifestFile();
  70666. }
  70667. }
  70668. }
  70669. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  70670. /**
  70671. * Gets a boolean indicating if scene must be saved in the database
  70672. */
  70673. get: function () {
  70674. return this._enableSceneOffline;
  70675. },
  70676. enumerable: true,
  70677. configurable: true
  70678. });
  70679. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  70680. /**
  70681. * Gets a boolean indicating if textures must be saved in the database
  70682. */
  70683. get: function () {
  70684. return this._enableTexturesOffline;
  70685. },
  70686. enumerable: true,
  70687. configurable: true
  70688. });
  70689. Database.prototype._checkManifestFile = function () {
  70690. var _this = this;
  70691. var noManifestFile = function () {
  70692. _this._enableSceneOffline = false;
  70693. _this._enableTexturesOffline = false;
  70694. _this.callbackManifestChecked(false);
  70695. };
  70696. var timeStampUsed = false;
  70697. var manifestURL = this.currentSceneUrl + ".manifest";
  70698. var xhr = new XMLHttpRequest();
  70699. if (navigator.onLine) {
  70700. // Adding a timestamp to by-pass browsers' cache
  70701. timeStampUsed = true;
  70702. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  70703. }
  70704. xhr.open("GET", manifestURL, true);
  70705. xhr.addEventListener("load", function () {
  70706. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70707. try {
  70708. var manifestFile = JSON.parse(xhr.response);
  70709. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  70710. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  70711. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  70712. _this.manifestVersionFound = manifestFile.version;
  70713. }
  70714. if (_this.callbackManifestChecked) {
  70715. _this.callbackManifestChecked(true);
  70716. }
  70717. }
  70718. catch (ex) {
  70719. noManifestFile();
  70720. }
  70721. }
  70722. else {
  70723. noManifestFile();
  70724. }
  70725. }, false);
  70726. xhr.addEventListener("error", function (event) {
  70727. if (timeStampUsed) {
  70728. timeStampUsed = false;
  70729. // Let's retry without the timeStamp
  70730. // It could fail when coupled with HTML5 Offline API
  70731. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  70732. xhr.open("GET", retryManifestURL, true);
  70733. xhr.send();
  70734. }
  70735. else {
  70736. noManifestFile();
  70737. }
  70738. }, false);
  70739. try {
  70740. xhr.send();
  70741. }
  70742. catch (ex) {
  70743. BABYLON.Tools.Error("Error on XHR send request.");
  70744. this.callbackManifestChecked(false);
  70745. }
  70746. };
  70747. /**
  70748. * Open the database and make it available
  70749. * @param successCallback defines the callback to call on success
  70750. * @param errorCallback defines the callback to call on error
  70751. */
  70752. Database.prototype.openAsync = function (successCallback, errorCallback) {
  70753. var _this = this;
  70754. var handleError = function () {
  70755. _this.isSupported = false;
  70756. if (errorCallback)
  70757. errorCallback();
  70758. };
  70759. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  70760. // Your browser doesn't support IndexedDB
  70761. this.isSupported = false;
  70762. if (errorCallback)
  70763. errorCallback();
  70764. }
  70765. else {
  70766. // If the DB hasn't been opened or created yet
  70767. if (!this.db) {
  70768. this.hasReachedQuota = false;
  70769. this.isSupported = true;
  70770. var request = this.idbFactory.open("babylonjs", 1);
  70771. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  70772. request.onerror = function (event) {
  70773. handleError();
  70774. };
  70775. // executes when a version change transaction cannot complete due to other active transactions
  70776. request.onblocked = function (event) {
  70777. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  70778. handleError();
  70779. };
  70780. // DB has been opened successfully
  70781. request.onsuccess = function (event) {
  70782. _this.db = request.result;
  70783. successCallback();
  70784. };
  70785. // Initialization of the DB. Creating Scenes & Textures stores
  70786. request.onupgradeneeded = function (event) {
  70787. _this.db = (event.target).result;
  70788. if (_this.db) {
  70789. try {
  70790. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  70791. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  70792. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  70793. }
  70794. catch (ex) {
  70795. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  70796. handleError();
  70797. }
  70798. }
  70799. };
  70800. }
  70801. // DB has already been created and opened
  70802. else {
  70803. if (successCallback)
  70804. successCallback();
  70805. }
  70806. }
  70807. };
  70808. /**
  70809. * Loads an image from the database
  70810. * @param url defines the url to load from
  70811. * @param image defines the target DOM image
  70812. */
  70813. Database.prototype.loadImageFromDB = function (url, image) {
  70814. var _this = this;
  70815. var completeURL = Database._ReturnFullUrlLocation(url);
  70816. var saveAndLoadImage = function () {
  70817. if (!_this.hasReachedQuota && _this.db !== null) {
  70818. // the texture is not yet in the DB, let's try to save it
  70819. _this._saveImageIntoDBAsync(completeURL, image);
  70820. }
  70821. // If the texture is not in the DB and we've reached the DB quota limit
  70822. // let's load it directly from the web
  70823. else {
  70824. image.src = url;
  70825. }
  70826. };
  70827. if (!this.mustUpdateRessources) {
  70828. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  70829. }
  70830. // First time we're download the images or update requested in the manifest file by a version change
  70831. else {
  70832. saveAndLoadImage();
  70833. }
  70834. };
  70835. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  70836. if (this.isSupported && this.db !== null) {
  70837. var texture;
  70838. var transaction = this.db.transaction(["textures"]);
  70839. transaction.onabort = function (event) {
  70840. image.src = url;
  70841. };
  70842. transaction.oncomplete = function (event) {
  70843. var blobTextureURL;
  70844. if (texture) {
  70845. var URL = window.URL || window.webkitURL;
  70846. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  70847. image.onerror = function () {
  70848. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  70849. image.src = url;
  70850. };
  70851. image.src = blobTextureURL;
  70852. }
  70853. else {
  70854. notInDBCallback();
  70855. }
  70856. };
  70857. var getRequest = transaction.objectStore("textures").get(url);
  70858. getRequest.onsuccess = function (event) {
  70859. texture = (event.target).result;
  70860. };
  70861. getRequest.onerror = function (event) {
  70862. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  70863. image.src = url;
  70864. };
  70865. }
  70866. else {
  70867. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70868. image.src = url;
  70869. }
  70870. };
  70871. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  70872. var _this = this;
  70873. if (this.isSupported) {
  70874. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  70875. var generateBlobUrl = function () {
  70876. var blobTextureURL;
  70877. if (blob) {
  70878. var URL = window.URL || window.webkitURL;
  70879. try {
  70880. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  70881. }
  70882. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  70883. catch (ex) {
  70884. blobTextureURL = URL.createObjectURL(blob);
  70885. }
  70886. }
  70887. if (blobTextureURL) {
  70888. image.src = blobTextureURL;
  70889. }
  70890. };
  70891. if (Database.IsUASupportingBlobStorage) { // Create XHR
  70892. var xhr = new XMLHttpRequest(), blob;
  70893. xhr.open("GET", url, true);
  70894. xhr.responseType = "blob";
  70895. xhr.addEventListener("load", function () {
  70896. if (xhr.status === 200 && _this.db) {
  70897. // Blob as response (XHR2)
  70898. blob = xhr.response;
  70899. var transaction = _this.db.transaction(["textures"], "readwrite");
  70900. // the transaction could abort because of a QuotaExceededError error
  70901. transaction.onabort = function (event) {
  70902. try {
  70903. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70904. var srcElement = (event.srcElement || event.target);
  70905. var error = srcElement.error;
  70906. if (error && error.name === "QuotaExceededError") {
  70907. _this.hasReachedQuota = true;
  70908. }
  70909. }
  70910. catch (ex) { }
  70911. generateBlobUrl();
  70912. };
  70913. transaction.oncomplete = function (event) {
  70914. generateBlobUrl();
  70915. };
  70916. var newTexture = { textureUrl: url, data: blob };
  70917. try {
  70918. // Put the blob into the dabase
  70919. var addRequest = transaction.objectStore("textures").put(newTexture);
  70920. addRequest.onsuccess = function (event) {
  70921. };
  70922. addRequest.onerror = function (event) {
  70923. generateBlobUrl();
  70924. };
  70925. }
  70926. catch (ex) {
  70927. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  70928. if (ex.code === 25) {
  70929. Database.IsUASupportingBlobStorage = false;
  70930. }
  70931. image.src = url;
  70932. }
  70933. }
  70934. else {
  70935. image.src = url;
  70936. }
  70937. }, false);
  70938. xhr.addEventListener("error", function (event) {
  70939. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  70940. image.src = url;
  70941. }, false);
  70942. xhr.send();
  70943. }
  70944. else {
  70945. image.src = url;
  70946. }
  70947. }
  70948. else {
  70949. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70950. image.src = url;
  70951. }
  70952. };
  70953. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  70954. var _this = this;
  70955. var updateVersion = function () {
  70956. // the version is not yet in the DB or we need to update it
  70957. _this._saveVersionIntoDBAsync(url, versionLoaded);
  70958. };
  70959. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  70960. };
  70961. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  70962. var _this = this;
  70963. if (this.isSupported && this.db) {
  70964. var version;
  70965. try {
  70966. var transaction = this.db.transaction(["versions"]);
  70967. transaction.oncomplete = function (event) {
  70968. if (version) {
  70969. // If the version in the JSON file is different from the version in DB
  70970. if (_this.manifestVersionFound !== version.data) {
  70971. _this.mustUpdateRessources = true;
  70972. updateInDBCallback();
  70973. }
  70974. else {
  70975. callback(version.data);
  70976. }
  70977. }
  70978. // version was not found in DB
  70979. else {
  70980. _this.mustUpdateRessources = true;
  70981. updateInDBCallback();
  70982. }
  70983. };
  70984. transaction.onabort = function (event) {
  70985. callback(-1);
  70986. };
  70987. var getRequest = transaction.objectStore("versions").get(url);
  70988. getRequest.onsuccess = function (event) {
  70989. version = (event.target).result;
  70990. };
  70991. getRequest.onerror = function (event) {
  70992. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  70993. callback(-1);
  70994. };
  70995. }
  70996. catch (ex) {
  70997. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  70998. callback(-1);
  70999. }
  71000. }
  71001. else {
  71002. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71003. callback(-1);
  71004. }
  71005. };
  71006. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  71007. var _this = this;
  71008. if (this.isSupported && !this.hasReachedQuota && this.db) {
  71009. try {
  71010. // Open a transaction to the database
  71011. var transaction = this.db.transaction(["versions"], "readwrite");
  71012. // the transaction could abort because of a QuotaExceededError error
  71013. transaction.onabort = function (event) {
  71014. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71015. var error = event.srcElement['error'];
  71016. if (error && error.name === "QuotaExceededError") {
  71017. _this.hasReachedQuota = true;
  71018. }
  71019. }
  71020. catch (ex) { }
  71021. callback(-1);
  71022. };
  71023. transaction.oncomplete = function (event) {
  71024. callback(_this.manifestVersionFound);
  71025. };
  71026. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  71027. // Put the scene into the database
  71028. var addRequest = transaction.objectStore("versions").put(newVersion);
  71029. addRequest.onsuccess = function (event) {
  71030. };
  71031. addRequest.onerror = function (event) {
  71032. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  71033. };
  71034. }
  71035. catch (ex) {
  71036. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  71037. callback(-1);
  71038. }
  71039. }
  71040. else {
  71041. callback(-1);
  71042. }
  71043. };
  71044. /**
  71045. * Loads a file from database
  71046. * @param url defines the URL to load from
  71047. * @param sceneLoaded defines a callback to call on success
  71048. * @param progressCallBack defines a callback to call when progress changed
  71049. * @param errorCallback defines a callback to call on error
  71050. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  71051. */
  71052. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  71053. var _this = this;
  71054. var completeUrl = Database._ReturnFullUrlLocation(url);
  71055. var saveAndLoadFile = function () {
  71056. // the scene is not yet in the DB, let's try to save it
  71057. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  71058. };
  71059. this._checkVersionFromDB(completeUrl, function (version) {
  71060. if (version !== -1) {
  71061. if (!_this.mustUpdateRessources) {
  71062. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  71063. }
  71064. else {
  71065. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  71066. }
  71067. }
  71068. else {
  71069. if (errorCallback) {
  71070. errorCallback();
  71071. }
  71072. }
  71073. });
  71074. };
  71075. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  71076. if (this.isSupported && this.db) {
  71077. var targetStore;
  71078. if (url.indexOf(".babylon") !== -1) {
  71079. targetStore = "scenes";
  71080. }
  71081. else {
  71082. targetStore = "textures";
  71083. }
  71084. var file;
  71085. var transaction = this.db.transaction([targetStore]);
  71086. transaction.oncomplete = function (event) {
  71087. if (file) {
  71088. callback(file.data);
  71089. }
  71090. // file was not found in DB
  71091. else {
  71092. notInDBCallback();
  71093. }
  71094. };
  71095. transaction.onabort = function (event) {
  71096. notInDBCallback();
  71097. };
  71098. var getRequest = transaction.objectStore(targetStore).get(url);
  71099. getRequest.onsuccess = function (event) {
  71100. file = (event.target).result;
  71101. };
  71102. getRequest.onerror = function (event) {
  71103. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  71104. notInDBCallback();
  71105. };
  71106. }
  71107. else {
  71108. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71109. callback();
  71110. }
  71111. };
  71112. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  71113. var _this = this;
  71114. if (this.isSupported) {
  71115. var targetStore;
  71116. if (url.indexOf(".babylon") !== -1) {
  71117. targetStore = "scenes";
  71118. }
  71119. else {
  71120. targetStore = "textures";
  71121. }
  71122. // Create XHR
  71123. var xhr = new XMLHttpRequest();
  71124. var fileData;
  71125. xhr.open("GET", url + "?" + Date.now(), true);
  71126. if (useArrayBuffer) {
  71127. xhr.responseType = "arraybuffer";
  71128. }
  71129. if (progressCallback) {
  71130. xhr.onprogress = progressCallback;
  71131. }
  71132. xhr.addEventListener("load", function () {
  71133. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  71134. // Blob as response (XHR2)
  71135. //fileData = xhr.responseText;
  71136. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  71137. if (!_this.hasReachedQuota && _this.db) {
  71138. // Open a transaction to the database
  71139. var transaction = _this.db.transaction([targetStore], "readwrite");
  71140. // the transaction could abort because of a QuotaExceededError error
  71141. transaction.onabort = function (event) {
  71142. try {
  71143. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71144. var error = event.srcElement['error'];
  71145. if (error && error.name === "QuotaExceededError") {
  71146. _this.hasReachedQuota = true;
  71147. }
  71148. }
  71149. catch (ex) { }
  71150. callback(fileData);
  71151. };
  71152. transaction.oncomplete = function (event) {
  71153. callback(fileData);
  71154. };
  71155. var newFile;
  71156. if (targetStore === "scenes") {
  71157. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  71158. }
  71159. else {
  71160. newFile = { textureUrl: url, data: fileData };
  71161. }
  71162. try {
  71163. // Put the scene into the database
  71164. var addRequest = transaction.objectStore(targetStore).put(newFile);
  71165. addRequest.onsuccess = function (event) {
  71166. };
  71167. addRequest.onerror = function (event) {
  71168. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  71169. };
  71170. }
  71171. catch (ex) {
  71172. callback(fileData);
  71173. }
  71174. }
  71175. else {
  71176. callback(fileData);
  71177. }
  71178. }
  71179. else {
  71180. if (xhr.status >= 400 && errorCallback) {
  71181. errorCallback(xhr);
  71182. }
  71183. else {
  71184. callback();
  71185. }
  71186. }
  71187. }, false);
  71188. xhr.addEventListener("error", function (event) {
  71189. BABYLON.Tools.Error("error on XHR request.");
  71190. callback();
  71191. }, false);
  71192. xhr.send();
  71193. }
  71194. else {
  71195. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71196. callback();
  71197. }
  71198. };
  71199. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  71200. Database.IsUASupportingBlobStorage = true;
  71201. /** Gets a boolean indicating if Database storate is enabled */
  71202. Database.IDBStorageEnabled = true;
  71203. Database._ParseURL = function (url) {
  71204. var a = document.createElement('a');
  71205. a.href = url;
  71206. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  71207. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  71208. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  71209. return absLocation;
  71210. };
  71211. Database._ReturnFullUrlLocation = function (url) {
  71212. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  71213. return (Database._ParseURL(window.location.href) + url);
  71214. }
  71215. else {
  71216. return url;
  71217. }
  71218. };
  71219. return Database;
  71220. }());
  71221. BABYLON.Database = Database;
  71222. })(BABYLON || (BABYLON = {}));
  71223. //# sourceMappingURL=babylon.database.js.map
  71224. var BABYLON;
  71225. (function (BABYLON) {
  71226. var FresnelParameters = /** @class */ (function () {
  71227. function FresnelParameters() {
  71228. this._isEnabled = true;
  71229. this.leftColor = BABYLON.Color3.White();
  71230. this.rightColor = BABYLON.Color3.Black();
  71231. this.bias = 0;
  71232. this.power = 1;
  71233. }
  71234. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  71235. get: function () {
  71236. return this._isEnabled;
  71237. },
  71238. set: function (value) {
  71239. if (this._isEnabled === value) {
  71240. return;
  71241. }
  71242. this._isEnabled = value;
  71243. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  71244. },
  71245. enumerable: true,
  71246. configurable: true
  71247. });
  71248. FresnelParameters.prototype.clone = function () {
  71249. var newFresnelParameters = new FresnelParameters();
  71250. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  71251. return newFresnelParameters;
  71252. };
  71253. FresnelParameters.prototype.serialize = function () {
  71254. var serializationObject = {};
  71255. serializationObject.isEnabled = this.isEnabled;
  71256. serializationObject.leftColor = this.leftColor.asArray();
  71257. serializationObject.rightColor = this.rightColor.asArray();
  71258. serializationObject.bias = this.bias;
  71259. serializationObject.power = this.power;
  71260. return serializationObject;
  71261. };
  71262. FresnelParameters.Parse = function (parsedFresnelParameters) {
  71263. var fresnelParameters = new FresnelParameters();
  71264. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  71265. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  71266. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  71267. fresnelParameters.bias = parsedFresnelParameters.bias;
  71268. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  71269. return fresnelParameters;
  71270. };
  71271. return FresnelParameters;
  71272. }());
  71273. BABYLON.FresnelParameters = FresnelParameters;
  71274. })(BABYLON || (BABYLON = {}));
  71275. //# sourceMappingURL=babylon.fresnelParameters.js.map
  71276. var BABYLON;
  71277. (function (BABYLON) {
  71278. var MultiMaterial = /** @class */ (function (_super) {
  71279. __extends(MultiMaterial, _super);
  71280. function MultiMaterial(name, scene) {
  71281. var _this = _super.call(this, name, scene, true) || this;
  71282. scene.multiMaterials.push(_this);
  71283. _this.subMaterials = new Array();
  71284. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  71285. return _this;
  71286. }
  71287. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  71288. get: function () {
  71289. return this._subMaterials;
  71290. },
  71291. set: function (value) {
  71292. this._subMaterials = value;
  71293. this._hookArray(value);
  71294. },
  71295. enumerable: true,
  71296. configurable: true
  71297. });
  71298. MultiMaterial.prototype._hookArray = function (array) {
  71299. var _this = this;
  71300. var oldPush = array.push;
  71301. array.push = function () {
  71302. var items = [];
  71303. for (var _i = 0; _i < arguments.length; _i++) {
  71304. items[_i] = arguments[_i];
  71305. }
  71306. var result = oldPush.apply(array, items);
  71307. _this._markAllSubMeshesAsTexturesDirty();
  71308. return result;
  71309. };
  71310. var oldSplice = array.splice;
  71311. array.splice = function (index, deleteCount) {
  71312. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71313. _this._markAllSubMeshesAsTexturesDirty();
  71314. return deleted;
  71315. };
  71316. };
  71317. // Properties
  71318. MultiMaterial.prototype.getSubMaterial = function (index) {
  71319. if (index < 0 || index >= this.subMaterials.length) {
  71320. return this.getScene().defaultMaterial;
  71321. }
  71322. return this.subMaterials[index];
  71323. };
  71324. MultiMaterial.prototype.getActiveTextures = function () {
  71325. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  71326. if (subMaterial) {
  71327. return subMaterial.getActiveTextures();
  71328. }
  71329. else {
  71330. return [];
  71331. }
  71332. }));
  71333. var _a;
  71334. };
  71335. // Methods
  71336. MultiMaterial.prototype.getClassName = function () {
  71337. return "MultiMaterial";
  71338. };
  71339. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71340. for (var index = 0; index < this.subMaterials.length; index++) {
  71341. var subMaterial = this.subMaterials[index];
  71342. if (subMaterial) {
  71343. if (subMaterial.storeEffectOnSubMeshes) {
  71344. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  71345. return false;
  71346. }
  71347. continue;
  71348. }
  71349. if (!subMaterial.isReady(mesh)) {
  71350. return false;
  71351. }
  71352. }
  71353. }
  71354. return true;
  71355. };
  71356. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  71357. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  71358. for (var index = 0; index < this.subMaterials.length; index++) {
  71359. var subMaterial = null;
  71360. var current = this.subMaterials[index];
  71361. if (cloneChildren && current) {
  71362. subMaterial = current.clone(name + "-" + current.name);
  71363. }
  71364. else {
  71365. subMaterial = this.subMaterials[index];
  71366. }
  71367. newMultiMaterial.subMaterials.push(subMaterial);
  71368. }
  71369. return newMultiMaterial;
  71370. };
  71371. MultiMaterial.prototype.serialize = function () {
  71372. var serializationObject = {};
  71373. serializationObject.name = this.name;
  71374. serializationObject.id = this.id;
  71375. if (BABYLON.Tags) {
  71376. serializationObject.tags = BABYLON.Tags.GetTags(this);
  71377. }
  71378. serializationObject.materials = [];
  71379. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  71380. var subMat = this.subMaterials[matIndex];
  71381. if (subMat) {
  71382. serializationObject.materials.push(subMat.id);
  71383. }
  71384. else {
  71385. serializationObject.materials.push(null);
  71386. }
  71387. }
  71388. return serializationObject;
  71389. };
  71390. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  71391. var scene = this.getScene();
  71392. if (!scene) {
  71393. return;
  71394. }
  71395. var index = scene.multiMaterials.indexOf(this);
  71396. if (index >= 0) {
  71397. scene.multiMaterials.splice(index, 1);
  71398. }
  71399. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  71400. };
  71401. return MultiMaterial;
  71402. }(BABYLON.Material));
  71403. BABYLON.MultiMaterial = MultiMaterial;
  71404. })(BABYLON || (BABYLON = {}));
  71405. //# sourceMappingURL=babylon.multiMaterial.js.map
  71406. var BABYLON;
  71407. (function (BABYLON) {
  71408. var FreeCameraTouchInput = /** @class */ (function () {
  71409. function FreeCameraTouchInput() {
  71410. this._offsetX = null;
  71411. this._offsetY = null;
  71412. this._pointerPressed = new Array();
  71413. this.touchAngularSensibility = 200000.0;
  71414. this.touchMoveSensibility = 250.0;
  71415. }
  71416. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  71417. var _this = this;
  71418. var previousPosition = null;
  71419. if (this._pointerInput === undefined) {
  71420. this._onLostFocus = function (evt) {
  71421. _this._offsetX = null;
  71422. _this._offsetY = null;
  71423. };
  71424. this._pointerInput = function (p, s) {
  71425. var evt = p.event;
  71426. if (evt.pointerType === "mouse") {
  71427. return;
  71428. }
  71429. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71430. if (!noPreventDefault) {
  71431. evt.preventDefault();
  71432. }
  71433. _this._pointerPressed.push(evt.pointerId);
  71434. if (_this._pointerPressed.length !== 1) {
  71435. return;
  71436. }
  71437. previousPosition = {
  71438. x: evt.clientX,
  71439. y: evt.clientY
  71440. };
  71441. }
  71442. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  71443. if (!noPreventDefault) {
  71444. evt.preventDefault();
  71445. }
  71446. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71447. if (index === -1) {
  71448. return;
  71449. }
  71450. _this._pointerPressed.splice(index, 1);
  71451. if (index != 0) {
  71452. return;
  71453. }
  71454. previousPosition = null;
  71455. _this._offsetX = null;
  71456. _this._offsetY = null;
  71457. }
  71458. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  71459. if (!noPreventDefault) {
  71460. evt.preventDefault();
  71461. }
  71462. if (!previousPosition) {
  71463. return;
  71464. }
  71465. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71466. if (index != 0) {
  71467. return;
  71468. }
  71469. _this._offsetX = evt.clientX - previousPosition.x;
  71470. _this._offsetY = -(evt.clientY - previousPosition.y);
  71471. }
  71472. };
  71473. }
  71474. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  71475. if (this._onLostFocus) {
  71476. element.addEventListener("blur", this._onLostFocus);
  71477. }
  71478. };
  71479. FreeCameraTouchInput.prototype.detachControl = function (element) {
  71480. if (this._pointerInput && element) {
  71481. if (this._observer) {
  71482. this.camera.getScene().onPointerObservable.remove(this._observer);
  71483. this._observer = null;
  71484. }
  71485. if (this._onLostFocus) {
  71486. element.removeEventListener("blur", this._onLostFocus);
  71487. this._onLostFocus = null;
  71488. }
  71489. this._pointerPressed = [];
  71490. this._offsetX = null;
  71491. this._offsetY = null;
  71492. }
  71493. };
  71494. FreeCameraTouchInput.prototype.checkInputs = function () {
  71495. if (this._offsetX && this._offsetY) {
  71496. var camera = this.camera;
  71497. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  71498. if (this._pointerPressed.length > 1) {
  71499. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  71500. }
  71501. else {
  71502. var speed = camera._computeLocalCameraSpeed();
  71503. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  71504. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  71505. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  71506. }
  71507. }
  71508. };
  71509. FreeCameraTouchInput.prototype.getClassName = function () {
  71510. return "FreeCameraTouchInput";
  71511. };
  71512. FreeCameraTouchInput.prototype.getSimpleName = function () {
  71513. return "touch";
  71514. };
  71515. __decorate([
  71516. BABYLON.serialize()
  71517. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  71518. __decorate([
  71519. BABYLON.serialize()
  71520. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  71521. return FreeCameraTouchInput;
  71522. }());
  71523. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  71524. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  71525. })(BABYLON || (BABYLON = {}));
  71526. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  71527. var BABYLON;
  71528. (function (BABYLON) {
  71529. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  71530. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  71531. });
  71532. // We're mainly based on the logic defined into the FreeCamera code
  71533. var TouchCamera = /** @class */ (function (_super) {
  71534. __extends(TouchCamera, _super);
  71535. //-- end properties for backward compatibility for inputs
  71536. function TouchCamera(name, position, scene) {
  71537. var _this = _super.call(this, name, position, scene) || this;
  71538. _this.inputs.addTouch();
  71539. _this._setupInputs();
  71540. return _this;
  71541. }
  71542. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  71543. //-- Begin properties for backward compatibility for inputs
  71544. get: function () {
  71545. var touch = this.inputs.attached["touch"];
  71546. if (touch)
  71547. return touch.touchAngularSensibility;
  71548. return 0;
  71549. },
  71550. set: function (value) {
  71551. var touch = this.inputs.attached["touch"];
  71552. if (touch)
  71553. touch.touchAngularSensibility = value;
  71554. },
  71555. enumerable: true,
  71556. configurable: true
  71557. });
  71558. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  71559. get: function () {
  71560. var touch = this.inputs.attached["touch"];
  71561. if (touch)
  71562. return touch.touchMoveSensibility;
  71563. return 0;
  71564. },
  71565. set: function (value) {
  71566. var touch = this.inputs.attached["touch"];
  71567. if (touch)
  71568. touch.touchMoveSensibility = value;
  71569. },
  71570. enumerable: true,
  71571. configurable: true
  71572. });
  71573. TouchCamera.prototype.getClassName = function () {
  71574. return "TouchCamera";
  71575. };
  71576. TouchCamera.prototype._setupInputs = function () {
  71577. var mouse = this.inputs.attached["mouse"];
  71578. if (mouse) {
  71579. mouse.touchEnabled = false;
  71580. }
  71581. };
  71582. return TouchCamera;
  71583. }(BABYLON.FreeCamera));
  71584. BABYLON.TouchCamera = TouchCamera;
  71585. })(BABYLON || (BABYLON = {}));
  71586. //# sourceMappingURL=babylon.touchCamera.js.map
  71587. var BABYLON;
  71588. (function (BABYLON) {
  71589. var ProceduralTexture = /** @class */ (function (_super) {
  71590. __extends(ProceduralTexture, _super);
  71591. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  71592. if (fallbackTexture === void 0) { fallbackTexture = null; }
  71593. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71594. if (isCube === void 0) { isCube = false; }
  71595. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71596. _this.isCube = isCube;
  71597. _this.isEnabled = true;
  71598. _this._currentRefreshId = -1;
  71599. _this._refreshRate = 1;
  71600. _this._vertexBuffers = {};
  71601. _this._uniforms = new Array();
  71602. _this._samplers = new Array();
  71603. _this._textures = {};
  71604. _this._floats = {};
  71605. _this._ints = {};
  71606. _this._floatsArrays = {};
  71607. _this._colors3 = {};
  71608. _this._colors4 = {};
  71609. _this._vectors2 = {};
  71610. _this._vectors3 = {};
  71611. _this._matrices = {};
  71612. _this._fallbackTextureUsed = false;
  71613. scene = _this.getScene();
  71614. scene.proceduralTextures.push(_this);
  71615. _this._engine = scene.getEngine();
  71616. _this.name = name;
  71617. _this.isRenderTarget = true;
  71618. _this._size = size;
  71619. _this._generateMipMaps = generateMipMaps;
  71620. _this.setFragment(fragment);
  71621. _this._fallbackTexture = fallbackTexture;
  71622. if (isCube) {
  71623. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  71624. _this.setFloat("face", 0);
  71625. }
  71626. else {
  71627. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  71628. }
  71629. // VBO
  71630. var vertices = [];
  71631. vertices.push(1, 1);
  71632. vertices.push(-1, 1);
  71633. vertices.push(-1, -1);
  71634. vertices.push(1, -1);
  71635. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71636. _this._createIndexBuffer();
  71637. return _this;
  71638. }
  71639. ProceduralTexture.prototype._createIndexBuffer = function () {
  71640. var engine = this._engine;
  71641. // Indices
  71642. var indices = [];
  71643. indices.push(0);
  71644. indices.push(1);
  71645. indices.push(2);
  71646. indices.push(0);
  71647. indices.push(2);
  71648. indices.push(3);
  71649. this._indexBuffer = engine.createIndexBuffer(indices);
  71650. };
  71651. ProceduralTexture.prototype._rebuild = function () {
  71652. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71653. if (vb) {
  71654. vb._rebuild();
  71655. }
  71656. this._createIndexBuffer();
  71657. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71658. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71659. }
  71660. };
  71661. ProceduralTexture.prototype.reset = function () {
  71662. if (this._effect === undefined) {
  71663. return;
  71664. }
  71665. var engine = this._engine;
  71666. engine._releaseEffect(this._effect);
  71667. };
  71668. ProceduralTexture.prototype.isReady = function () {
  71669. var _this = this;
  71670. var engine = this._engine;
  71671. var shaders;
  71672. if (!this._fragment) {
  71673. return false;
  71674. }
  71675. if (this._fallbackTextureUsed) {
  71676. return true;
  71677. }
  71678. if (this._fragment.fragmentElement !== undefined) {
  71679. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  71680. }
  71681. else {
  71682. shaders = { vertex: "procedural", fragment: this._fragment };
  71683. }
  71684. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  71685. _this.releaseInternalTexture();
  71686. if (_this._fallbackTexture) {
  71687. _this._texture = _this._fallbackTexture._texture;
  71688. if (_this._texture) {
  71689. _this._texture.incrementReferences();
  71690. }
  71691. }
  71692. _this._fallbackTextureUsed = true;
  71693. });
  71694. return this._effect.isReady();
  71695. };
  71696. ProceduralTexture.prototype.resetRefreshCounter = function () {
  71697. this._currentRefreshId = -1;
  71698. };
  71699. ProceduralTexture.prototype.setFragment = function (fragment) {
  71700. this._fragment = fragment;
  71701. };
  71702. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  71703. get: function () {
  71704. return this._refreshRate;
  71705. },
  71706. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71707. set: function (value) {
  71708. this._refreshRate = value;
  71709. this.resetRefreshCounter();
  71710. },
  71711. enumerable: true,
  71712. configurable: true
  71713. });
  71714. ProceduralTexture.prototype._shouldRender = function () {
  71715. if (!this.isEnabled || !this.isReady() || !this._texture) {
  71716. return false;
  71717. }
  71718. if (this._fallbackTextureUsed) {
  71719. return false;
  71720. }
  71721. if (this._currentRefreshId === -1) { // At least render once
  71722. this._currentRefreshId = 1;
  71723. return true;
  71724. }
  71725. if (this.refreshRate === this._currentRefreshId) {
  71726. this._currentRefreshId = 1;
  71727. return true;
  71728. }
  71729. this._currentRefreshId++;
  71730. return false;
  71731. };
  71732. ProceduralTexture.prototype.getRenderSize = function () {
  71733. return this._size;
  71734. };
  71735. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  71736. if (this._fallbackTextureUsed) {
  71737. return;
  71738. }
  71739. this.releaseInternalTexture();
  71740. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  71741. // Update properties
  71742. this._size = size;
  71743. this._generateMipMaps = generateMipMaps;
  71744. };
  71745. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  71746. if (this._uniforms.indexOf(uniformName) === -1) {
  71747. this._uniforms.push(uniformName);
  71748. }
  71749. };
  71750. ProceduralTexture.prototype.setTexture = function (name, texture) {
  71751. if (this._samplers.indexOf(name) === -1) {
  71752. this._samplers.push(name);
  71753. }
  71754. this._textures[name] = texture;
  71755. return this;
  71756. };
  71757. ProceduralTexture.prototype.setFloat = function (name, value) {
  71758. this._checkUniform(name);
  71759. this._floats[name] = value;
  71760. return this;
  71761. };
  71762. /**
  71763. * Set the value of an uniform to an integer value
  71764. * @param name defines the name of the uniform
  71765. * @param value defines the value to set
  71766. * @returns the current procedural texture
  71767. */
  71768. ProceduralTexture.prototype.setInt = function (name, value) {
  71769. this._checkUniform(name);
  71770. this._ints[name] = value;
  71771. return this;
  71772. };
  71773. ProceduralTexture.prototype.setFloats = function (name, value) {
  71774. this._checkUniform(name);
  71775. this._floatsArrays[name] = value;
  71776. return this;
  71777. };
  71778. ProceduralTexture.prototype.setColor3 = function (name, value) {
  71779. this._checkUniform(name);
  71780. this._colors3[name] = value;
  71781. return this;
  71782. };
  71783. ProceduralTexture.prototype.setColor4 = function (name, value) {
  71784. this._checkUniform(name);
  71785. this._colors4[name] = value;
  71786. return this;
  71787. };
  71788. ProceduralTexture.prototype.setVector2 = function (name, value) {
  71789. this._checkUniform(name);
  71790. this._vectors2[name] = value;
  71791. return this;
  71792. };
  71793. ProceduralTexture.prototype.setVector3 = function (name, value) {
  71794. this._checkUniform(name);
  71795. this._vectors3[name] = value;
  71796. return this;
  71797. };
  71798. ProceduralTexture.prototype.setMatrix = function (name, value) {
  71799. this._checkUniform(name);
  71800. this._matrices[name] = value;
  71801. return this;
  71802. };
  71803. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71804. var scene = this.getScene();
  71805. if (!scene) {
  71806. return;
  71807. }
  71808. var engine = this._engine;
  71809. // Render
  71810. engine.enableEffect(this._effect);
  71811. engine.setState(false);
  71812. // Texture
  71813. for (var name in this._textures) {
  71814. this._effect.setTexture(name, this._textures[name]);
  71815. }
  71816. // Float
  71817. for (name in this._ints) {
  71818. this._effect.setInt(name, this._ints[name]);
  71819. }
  71820. // Float
  71821. for (name in this._floats) {
  71822. this._effect.setFloat(name, this._floats[name]);
  71823. }
  71824. // Floats
  71825. for (name in this._floatsArrays) {
  71826. this._effect.setArray(name, this._floatsArrays[name]);
  71827. }
  71828. // Color3
  71829. for (name in this._colors3) {
  71830. this._effect.setColor3(name, this._colors3[name]);
  71831. }
  71832. // Color4
  71833. for (name in this._colors4) {
  71834. var color = this._colors4[name];
  71835. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  71836. }
  71837. // Vector2
  71838. for (name in this._vectors2) {
  71839. this._effect.setVector2(name, this._vectors2[name]);
  71840. }
  71841. // Vector3
  71842. for (name in this._vectors3) {
  71843. this._effect.setVector3(name, this._vectors3[name]);
  71844. }
  71845. // Matrix
  71846. for (name in this._matrices) {
  71847. this._effect.setMatrix(name, this._matrices[name]);
  71848. }
  71849. if (!this._texture) {
  71850. return;
  71851. }
  71852. if (this.isCube) {
  71853. for (var face = 0; face < 6; face++) {
  71854. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  71855. // VBOs
  71856. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71857. this._effect.setFloat("face", face);
  71858. // Clear
  71859. engine.clear(scene.clearColor, true, true, true);
  71860. // Draw order
  71861. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71862. // Mipmaps
  71863. if (face === 5) {
  71864. engine.generateMipMapsForCubemap(this._texture);
  71865. }
  71866. }
  71867. }
  71868. else {
  71869. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  71870. // VBOs
  71871. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71872. // Clear
  71873. engine.clear(scene.clearColor, true, true, true);
  71874. // Draw order
  71875. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71876. }
  71877. // Unbind
  71878. engine.unBindFramebuffer(this._texture, this.isCube);
  71879. if (this.onGenerated) {
  71880. this.onGenerated();
  71881. }
  71882. };
  71883. ProceduralTexture.prototype.clone = function () {
  71884. var textureSize = this.getSize();
  71885. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  71886. // Base texture
  71887. newTexture.hasAlpha = this.hasAlpha;
  71888. newTexture.level = this.level;
  71889. // RenderTarget Texture
  71890. newTexture.coordinatesMode = this.coordinatesMode;
  71891. return newTexture;
  71892. };
  71893. ProceduralTexture.prototype.dispose = function () {
  71894. var scene = this.getScene();
  71895. if (!scene) {
  71896. return;
  71897. }
  71898. var index = scene.proceduralTextures.indexOf(this);
  71899. if (index >= 0) {
  71900. scene.proceduralTextures.splice(index, 1);
  71901. }
  71902. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71903. if (vertexBuffer) {
  71904. vertexBuffer.dispose();
  71905. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71906. }
  71907. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  71908. this._indexBuffer = null;
  71909. }
  71910. _super.prototype.dispose.call(this);
  71911. };
  71912. __decorate([
  71913. BABYLON.serialize()
  71914. ], ProceduralTexture.prototype, "_size", void 0);
  71915. __decorate([
  71916. BABYLON.serialize()
  71917. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  71918. __decorate([
  71919. BABYLON.serialize()
  71920. ], ProceduralTexture.prototype, "isEnabled", void 0);
  71921. __decorate([
  71922. BABYLON.serialize()
  71923. ], ProceduralTexture.prototype, "refreshRate", null);
  71924. return ProceduralTexture;
  71925. }(BABYLON.Texture));
  71926. BABYLON.ProceduralTexture = ProceduralTexture;
  71927. })(BABYLON || (BABYLON = {}));
  71928. //# sourceMappingURL=babylon.proceduralTexture.js.map
  71929. var BABYLON;
  71930. (function (BABYLON) {
  71931. var CustomProceduralTexture = /** @class */ (function (_super) {
  71932. __extends(CustomProceduralTexture, _super);
  71933. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  71934. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  71935. _this._animate = true;
  71936. _this._time = 0;
  71937. _this._texturePath = texturePath;
  71938. //Try to load json
  71939. _this.loadJson(texturePath);
  71940. _this.refreshRate = 1;
  71941. return _this;
  71942. }
  71943. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  71944. var _this = this;
  71945. var noConfigFile = function () {
  71946. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  71947. try {
  71948. _this.setFragment(_this._texturePath);
  71949. }
  71950. catch (ex) {
  71951. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  71952. }
  71953. };
  71954. var configFileUrl = jsonUrl + "/config.json";
  71955. var xhr = new XMLHttpRequest();
  71956. xhr.open("GET", configFileUrl, true);
  71957. xhr.addEventListener("load", function () {
  71958. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71959. try {
  71960. _this._config = JSON.parse(xhr.response);
  71961. _this.updateShaderUniforms();
  71962. _this.updateTextures();
  71963. _this.setFragment(_this._texturePath + "/custom");
  71964. _this._animate = _this._config.animate;
  71965. _this.refreshRate = _this._config.refreshrate;
  71966. }
  71967. catch (ex) {
  71968. noConfigFile();
  71969. }
  71970. }
  71971. else {
  71972. noConfigFile();
  71973. }
  71974. }, false);
  71975. xhr.addEventListener("error", function () {
  71976. noConfigFile();
  71977. }, false);
  71978. try {
  71979. xhr.send();
  71980. }
  71981. catch (ex) {
  71982. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  71983. }
  71984. };
  71985. CustomProceduralTexture.prototype.isReady = function () {
  71986. if (!_super.prototype.isReady.call(this)) {
  71987. return false;
  71988. }
  71989. for (var name in this._textures) {
  71990. var texture = this._textures[name];
  71991. if (!texture.isReady()) {
  71992. return false;
  71993. }
  71994. }
  71995. return true;
  71996. };
  71997. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71998. var scene = this.getScene();
  71999. if (this._animate && scene) {
  72000. this._time += scene.getAnimationRatio() * 0.03;
  72001. this.updateShaderUniforms();
  72002. }
  72003. _super.prototype.render.call(this, useCameraPostProcess);
  72004. };
  72005. CustomProceduralTexture.prototype.updateTextures = function () {
  72006. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  72007. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  72008. }
  72009. };
  72010. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  72011. if (this._config) {
  72012. for (var j = 0; j < this._config.uniforms.length; j++) {
  72013. var uniform = this._config.uniforms[j];
  72014. switch (uniform.type) {
  72015. case "float":
  72016. this.setFloat(uniform.name, uniform.value);
  72017. break;
  72018. case "color3":
  72019. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  72020. break;
  72021. case "color4":
  72022. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  72023. break;
  72024. case "vector2":
  72025. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  72026. break;
  72027. case "vector3":
  72028. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  72029. break;
  72030. }
  72031. }
  72032. }
  72033. this.setFloat("time", this._time);
  72034. };
  72035. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  72036. get: function () {
  72037. return this._animate;
  72038. },
  72039. set: function (value) {
  72040. this._animate = value;
  72041. },
  72042. enumerable: true,
  72043. configurable: true
  72044. });
  72045. return CustomProceduralTexture;
  72046. }(BABYLON.ProceduralTexture));
  72047. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  72048. })(BABYLON || (BABYLON = {}));
  72049. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  72050. var BABYLON;
  72051. (function (BABYLON) {
  72052. var FreeCameraGamepadInput = /** @class */ (function () {
  72053. function FreeCameraGamepadInput() {
  72054. this.gamepadAngularSensibility = 200;
  72055. this.gamepadMoveSensibility = 40;
  72056. // private members
  72057. this._cameraTransform = BABYLON.Matrix.Identity();
  72058. this._deltaTransform = BABYLON.Vector3.Zero();
  72059. this._vector3 = BABYLON.Vector3.Zero();
  72060. this._vector2 = BABYLON.Vector2.Zero();
  72061. }
  72062. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72063. var _this = this;
  72064. var manager = this.camera.getScene().gamepadManager;
  72065. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72066. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72067. // prioritize XBOX gamepads.
  72068. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72069. _this.gamepad = gamepad;
  72070. }
  72071. }
  72072. });
  72073. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72074. if (_this.gamepad === gamepad) {
  72075. _this.gamepad = null;
  72076. }
  72077. });
  72078. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72079. };
  72080. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  72081. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72082. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72083. this.gamepad = null;
  72084. };
  72085. FreeCameraGamepadInput.prototype.checkInputs = function () {
  72086. if (this.gamepad && this.gamepad.leftStick) {
  72087. var camera = this.camera;
  72088. var LSValues = this.gamepad.leftStick;
  72089. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  72090. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72091. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  72092. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  72093. var RSValues = this.gamepad.rightStick;
  72094. if (RSValues) {
  72095. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  72096. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  72097. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  72098. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  72099. }
  72100. else {
  72101. RSValues = { x: 0, y: 0 };
  72102. }
  72103. if (!camera.rotationQuaternion) {
  72104. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  72105. }
  72106. else {
  72107. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  72108. }
  72109. var speed = camera._computeLocalCameraSpeed() * 50.0;
  72110. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  72111. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  72112. camera.cameraDirection.addInPlace(this._deltaTransform);
  72113. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  72114. camera.cameraRotation.addInPlace(this._vector2);
  72115. }
  72116. };
  72117. FreeCameraGamepadInput.prototype.getClassName = function () {
  72118. return "FreeCameraGamepadInput";
  72119. };
  72120. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  72121. return "gamepad";
  72122. };
  72123. __decorate([
  72124. BABYLON.serialize()
  72125. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  72126. __decorate([
  72127. BABYLON.serialize()
  72128. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72129. return FreeCameraGamepadInput;
  72130. }());
  72131. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  72132. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  72133. })(BABYLON || (BABYLON = {}));
  72134. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  72135. var BABYLON;
  72136. (function (BABYLON) {
  72137. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  72138. function ArcRotateCameraGamepadInput() {
  72139. this.gamepadRotationSensibility = 80;
  72140. this.gamepadMoveSensibility = 40;
  72141. }
  72142. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72143. var _this = this;
  72144. var manager = this.camera.getScene().gamepadManager;
  72145. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72146. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72147. // prioritize XBOX gamepads.
  72148. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72149. _this.gamepad = gamepad;
  72150. }
  72151. }
  72152. });
  72153. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72154. if (_this.gamepad === gamepad) {
  72155. _this.gamepad = null;
  72156. }
  72157. });
  72158. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72159. };
  72160. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  72161. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72162. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72163. this.gamepad = null;
  72164. };
  72165. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  72166. if (this.gamepad) {
  72167. var camera = this.camera;
  72168. var RSValues = this.gamepad.rightStick;
  72169. if (RSValues) {
  72170. if (RSValues.x != 0) {
  72171. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  72172. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  72173. camera.inertialAlphaOffset += normalizedRX;
  72174. }
  72175. }
  72176. if (RSValues.y != 0) {
  72177. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  72178. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  72179. camera.inertialBetaOffset += normalizedRY;
  72180. }
  72181. }
  72182. }
  72183. var LSValues = this.gamepad.leftStick;
  72184. if (LSValues && LSValues.y != 0) {
  72185. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72186. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  72187. this.camera.inertialRadiusOffset -= normalizedLY;
  72188. }
  72189. }
  72190. }
  72191. };
  72192. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  72193. return "ArcRotateCameraGamepadInput";
  72194. };
  72195. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  72196. return "gamepad";
  72197. };
  72198. __decorate([
  72199. BABYLON.serialize()
  72200. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  72201. __decorate([
  72202. BABYLON.serialize()
  72203. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72204. return ArcRotateCameraGamepadInput;
  72205. }());
  72206. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  72207. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  72208. })(BABYLON || (BABYLON = {}));
  72209. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  72210. var BABYLON;
  72211. (function (BABYLON) {
  72212. var GamepadManager = /** @class */ (function () {
  72213. function GamepadManager(_scene) {
  72214. var _this = this;
  72215. this._scene = _scene;
  72216. this._babylonGamepads = [];
  72217. this._oneGamepadConnected = false;
  72218. this._isMonitoring = false;
  72219. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  72220. if (!BABYLON.Tools.IsWindowObjectExist()) {
  72221. this._gamepadEventSupported = false;
  72222. }
  72223. else {
  72224. this._gamepadEventSupported = 'GamepadEvent' in window;
  72225. this._gamepadSupport = (navigator.getGamepads ||
  72226. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  72227. }
  72228. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  72229. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  72230. for (var i in _this._babylonGamepads) {
  72231. var gamepad = _this._babylonGamepads[i];
  72232. if (gamepad && gamepad._isConnected) {
  72233. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  72234. }
  72235. }
  72236. });
  72237. this._onGamepadConnectedEvent = function (evt) {
  72238. var gamepad = evt.gamepad;
  72239. if (gamepad.index in _this._babylonGamepads) {
  72240. if (_this._babylonGamepads[gamepad.index].isConnected) {
  72241. return;
  72242. }
  72243. }
  72244. var newGamepad;
  72245. if (_this._babylonGamepads[gamepad.index]) {
  72246. newGamepad = _this._babylonGamepads[gamepad.index];
  72247. newGamepad.browserGamepad = gamepad;
  72248. newGamepad._isConnected = true;
  72249. }
  72250. else {
  72251. newGamepad = _this._addNewGamepad(gamepad);
  72252. }
  72253. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72254. _this._startMonitoringGamepads();
  72255. };
  72256. this._onGamepadDisconnectedEvent = function (evt) {
  72257. var gamepad = evt.gamepad;
  72258. // Remove the gamepad from the list of gamepads to monitor.
  72259. for (var i in _this._babylonGamepads) {
  72260. if (_this._babylonGamepads[i].index === gamepad.index) {
  72261. var disconnectedGamepad = _this._babylonGamepads[i];
  72262. disconnectedGamepad._isConnected = false;
  72263. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  72264. break;
  72265. }
  72266. }
  72267. };
  72268. if (this._gamepadSupport) {
  72269. //first add already-connected gamepads
  72270. this._updateGamepadObjects();
  72271. if (this._babylonGamepads.length) {
  72272. this._startMonitoringGamepads();
  72273. }
  72274. // Checking if the gamepad connected event is supported (like in Firefox)
  72275. if (this._gamepadEventSupported) {
  72276. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  72277. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  72278. }
  72279. else {
  72280. this._startMonitoringGamepads();
  72281. }
  72282. }
  72283. }
  72284. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  72285. get: function () {
  72286. return this._babylonGamepads;
  72287. },
  72288. enumerable: true,
  72289. configurable: true
  72290. });
  72291. GamepadManager.prototype.getGamepadByType = function (type) {
  72292. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  72293. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  72294. var gamepad = _a[_i];
  72295. if (gamepad && gamepad.type === type) {
  72296. return gamepad;
  72297. }
  72298. }
  72299. return null;
  72300. };
  72301. GamepadManager.prototype.dispose = function () {
  72302. if (this._gamepadEventSupported) {
  72303. if (this._onGamepadConnectedEvent) {
  72304. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  72305. }
  72306. if (this._onGamepadDisconnectedEvent) {
  72307. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  72308. }
  72309. this._onGamepadConnectedEvent = null;
  72310. this._onGamepadDisconnectedEvent = null;
  72311. }
  72312. this._babylonGamepads.forEach(function (gamepad) {
  72313. gamepad.dispose();
  72314. });
  72315. this.onGamepadConnectedObservable.clear();
  72316. this.onGamepadDisconnectedObservable.clear();
  72317. this._oneGamepadConnected = false;
  72318. this._stopMonitoringGamepads();
  72319. this._babylonGamepads = [];
  72320. };
  72321. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  72322. if (!this._oneGamepadConnected) {
  72323. this._oneGamepadConnected = true;
  72324. }
  72325. var newGamepad;
  72326. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  72327. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  72328. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  72329. }
  72330. // if pose is supported, use the (WebVR) pose enabled controller
  72331. else if (gamepad.pose) {
  72332. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  72333. }
  72334. else {
  72335. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  72336. }
  72337. this._babylonGamepads[newGamepad.index] = newGamepad;
  72338. return newGamepad;
  72339. };
  72340. GamepadManager.prototype._startMonitoringGamepads = function () {
  72341. if (!this._isMonitoring) {
  72342. this._isMonitoring = true;
  72343. //back-comp
  72344. if (!this._scene) {
  72345. this._checkGamepadsStatus();
  72346. }
  72347. }
  72348. };
  72349. GamepadManager.prototype._stopMonitoringGamepads = function () {
  72350. this._isMonitoring = false;
  72351. };
  72352. GamepadManager.prototype._checkGamepadsStatus = function () {
  72353. var _this = this;
  72354. // Hack to be compatible Chrome
  72355. this._updateGamepadObjects();
  72356. for (var i in this._babylonGamepads) {
  72357. var gamepad = this._babylonGamepads[i];
  72358. if (!gamepad || !gamepad.isConnected) {
  72359. continue;
  72360. }
  72361. gamepad.update();
  72362. }
  72363. if (this._isMonitoring && !this._scene) {
  72364. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  72365. }
  72366. };
  72367. // This function is called only on Chrome, which does not properly support
  72368. // connection/disconnection events and forces you to recopy again the gamepad object
  72369. GamepadManager.prototype._updateGamepadObjects = function () {
  72370. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  72371. for (var i = 0; i < gamepads.length; i++) {
  72372. var gamepad = gamepads[i];
  72373. if (gamepad) {
  72374. if (!this._babylonGamepads[gamepad.index]) {
  72375. var newGamepad = this._addNewGamepad(gamepad);
  72376. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72377. }
  72378. else {
  72379. // Forced to copy again this object for Chrome for unknown reason
  72380. this._babylonGamepads[i].browserGamepad = gamepad;
  72381. if (!this._babylonGamepads[i].isConnected) {
  72382. this._babylonGamepads[i]._isConnected = true;
  72383. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  72384. }
  72385. }
  72386. }
  72387. }
  72388. };
  72389. return GamepadManager;
  72390. }());
  72391. BABYLON.GamepadManager = GamepadManager;
  72392. })(BABYLON || (BABYLON = {}));
  72393. //# sourceMappingURL=babylon.gamepadManager.js.map
  72394. var BABYLON;
  72395. (function (BABYLON) {
  72396. var StickValues = /** @class */ (function () {
  72397. function StickValues(x, y) {
  72398. this.x = x;
  72399. this.y = y;
  72400. }
  72401. return StickValues;
  72402. }());
  72403. BABYLON.StickValues = StickValues;
  72404. var Gamepad = /** @class */ (function () {
  72405. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  72406. if (leftStickX === void 0) { leftStickX = 0; }
  72407. if (leftStickY === void 0) { leftStickY = 1; }
  72408. if (rightStickX === void 0) { rightStickX = 2; }
  72409. if (rightStickY === void 0) { rightStickY = 3; }
  72410. this.id = id;
  72411. this.index = index;
  72412. this.browserGamepad = browserGamepad;
  72413. this._isConnected = true;
  72414. this._invertLeftStickY = false;
  72415. this.type = Gamepad.GAMEPAD;
  72416. this._leftStickAxisX = leftStickX;
  72417. this._leftStickAxisY = leftStickY;
  72418. this._rightStickAxisX = rightStickX;
  72419. this._rightStickAxisY = rightStickY;
  72420. if (this.browserGamepad.axes.length >= 2) {
  72421. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72422. }
  72423. if (this.browserGamepad.axes.length >= 4) {
  72424. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72425. }
  72426. }
  72427. Object.defineProperty(Gamepad.prototype, "isConnected", {
  72428. get: function () {
  72429. return this._isConnected;
  72430. },
  72431. enumerable: true,
  72432. configurable: true
  72433. });
  72434. Gamepad.prototype.onleftstickchanged = function (callback) {
  72435. this._onleftstickchanged = callback;
  72436. };
  72437. Gamepad.prototype.onrightstickchanged = function (callback) {
  72438. this._onrightstickchanged = callback;
  72439. };
  72440. Object.defineProperty(Gamepad.prototype, "leftStick", {
  72441. get: function () {
  72442. return this._leftStick;
  72443. },
  72444. set: function (newValues) {
  72445. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  72446. this._onleftstickchanged(newValues);
  72447. }
  72448. this._leftStick = newValues;
  72449. },
  72450. enumerable: true,
  72451. configurable: true
  72452. });
  72453. Object.defineProperty(Gamepad.prototype, "rightStick", {
  72454. get: function () {
  72455. return this._rightStick;
  72456. },
  72457. set: function (newValues) {
  72458. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  72459. this._onrightstickchanged(newValues);
  72460. }
  72461. this._rightStick = newValues;
  72462. },
  72463. enumerable: true,
  72464. configurable: true
  72465. });
  72466. Gamepad.prototype.update = function () {
  72467. if (this._leftStick) {
  72468. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72469. if (this._invertLeftStickY) {
  72470. this.leftStick.y *= -1;
  72471. }
  72472. }
  72473. if (this._rightStick) {
  72474. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72475. }
  72476. };
  72477. Gamepad.prototype.dispose = function () {
  72478. };
  72479. Gamepad.GAMEPAD = 0;
  72480. Gamepad.GENERIC = 1;
  72481. Gamepad.XBOX = 2;
  72482. Gamepad.POSE_ENABLED = 3;
  72483. return Gamepad;
  72484. }());
  72485. BABYLON.Gamepad = Gamepad;
  72486. var GenericPad = /** @class */ (function (_super) {
  72487. __extends(GenericPad, _super);
  72488. function GenericPad(id, index, browserGamepad) {
  72489. var _this = _super.call(this, id, index, browserGamepad) || this;
  72490. _this.onButtonDownObservable = new BABYLON.Observable();
  72491. _this.onButtonUpObservable = new BABYLON.Observable();
  72492. _this.type = Gamepad.GENERIC;
  72493. _this._buttons = new Array(browserGamepad.buttons.length);
  72494. return _this;
  72495. }
  72496. GenericPad.prototype.onbuttondown = function (callback) {
  72497. this._onbuttondown = callback;
  72498. };
  72499. GenericPad.prototype.onbuttonup = function (callback) {
  72500. this._onbuttonup = callback;
  72501. };
  72502. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  72503. if (newValue !== currentValue) {
  72504. if (newValue === 1) {
  72505. if (this._onbuttondown) {
  72506. this._onbuttondown(buttonIndex);
  72507. }
  72508. this.onButtonDownObservable.notifyObservers(buttonIndex);
  72509. }
  72510. if (newValue === 0) {
  72511. if (this._onbuttonup) {
  72512. this._onbuttonup(buttonIndex);
  72513. }
  72514. this.onButtonUpObservable.notifyObservers(buttonIndex);
  72515. }
  72516. }
  72517. return newValue;
  72518. };
  72519. GenericPad.prototype.update = function () {
  72520. _super.prototype.update.call(this);
  72521. for (var index = 0; index < this._buttons.length; index++) {
  72522. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  72523. }
  72524. };
  72525. GenericPad.prototype.dispose = function () {
  72526. _super.prototype.dispose.call(this);
  72527. this.onButtonDownObservable.clear();
  72528. this.onButtonUpObservable.clear();
  72529. };
  72530. return GenericPad;
  72531. }(Gamepad));
  72532. BABYLON.GenericPad = GenericPad;
  72533. })(BABYLON || (BABYLON = {}));
  72534. //# sourceMappingURL=babylon.gamepad.js.map
  72535. var BABYLON;
  72536. (function (BABYLON) {
  72537. /**
  72538. * Defines supported buttons for XBox360 compatible gamepads
  72539. */
  72540. var Xbox360Button;
  72541. (function (Xbox360Button) {
  72542. /** A */
  72543. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  72544. /** B */
  72545. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  72546. /** X */
  72547. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  72548. /** Y */
  72549. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  72550. /** Start */
  72551. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  72552. /** Back */
  72553. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  72554. /** Left button */
  72555. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  72556. /** Right button */
  72557. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  72558. /** Left stick */
  72559. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  72560. /** Right stick */
  72561. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  72562. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  72563. /** Defines values for XBox360 DPad */
  72564. var Xbox360Dpad;
  72565. (function (Xbox360Dpad) {
  72566. /** Up */
  72567. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  72568. /** Down */
  72569. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  72570. /** Left */
  72571. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  72572. /** Right */
  72573. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  72574. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  72575. /**
  72576. * Defines a XBox360 gamepad
  72577. */
  72578. var Xbox360Pad = /** @class */ (function (_super) {
  72579. __extends(Xbox360Pad, _super);
  72580. /**
  72581. * Creates a new XBox360 gamepad object
  72582. * @param id defines the id of this gamepad
  72583. * @param index defines its index
  72584. * @param gamepad defines the internal HTML gamepad object
  72585. * @param xboxOne defines if it is a XBox One gamepad
  72586. */
  72587. function Xbox360Pad(id, index, gamepad, xboxOne) {
  72588. if (xboxOne === void 0) { xboxOne = false; }
  72589. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  72590. _this._leftTrigger = 0;
  72591. _this._rightTrigger = 0;
  72592. /** Observable raised when a button is pressed */
  72593. _this.onButtonDownObservable = new BABYLON.Observable();
  72594. /** Observable raised when a button is released */
  72595. _this.onButtonUpObservable = new BABYLON.Observable();
  72596. /** Observable raised when a pad is pressed */
  72597. _this.onPadDownObservable = new BABYLON.Observable();
  72598. /** Observable raised when a pad is released */
  72599. _this.onPadUpObservable = new BABYLON.Observable();
  72600. _this._buttonA = 0;
  72601. _this._buttonB = 0;
  72602. _this._buttonX = 0;
  72603. _this._buttonY = 0;
  72604. _this._buttonBack = 0;
  72605. _this._buttonStart = 0;
  72606. _this._buttonLB = 0;
  72607. _this._buttonRB = 0;
  72608. _this._buttonLeftStick = 0;
  72609. _this._buttonRightStick = 0;
  72610. _this._dPadUp = 0;
  72611. _this._dPadDown = 0;
  72612. _this._dPadLeft = 0;
  72613. _this._dPadRight = 0;
  72614. _this._isXboxOnePad = false;
  72615. _this.type = BABYLON.Gamepad.XBOX;
  72616. _this._isXboxOnePad = xboxOne;
  72617. return _this;
  72618. }
  72619. /**
  72620. * Defines the callback to call when left trigger is pressed
  72621. * @param callback defines the callback to use
  72622. */
  72623. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  72624. this._onlefttriggerchanged = callback;
  72625. };
  72626. /**
  72627. * Defines the callback to call when right trigger is pressed
  72628. * @param callback defines the callback to use
  72629. */
  72630. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  72631. this._onrighttriggerchanged = callback;
  72632. };
  72633. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  72634. /**
  72635. * Gets or sets left trigger value
  72636. */
  72637. get: function () {
  72638. return this._leftTrigger;
  72639. },
  72640. set: function (newValue) {
  72641. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  72642. this._onlefttriggerchanged(newValue);
  72643. }
  72644. this._leftTrigger = newValue;
  72645. },
  72646. enumerable: true,
  72647. configurable: true
  72648. });
  72649. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  72650. /**
  72651. * Gets or sets right trigger value
  72652. */
  72653. get: function () {
  72654. return this._rightTrigger;
  72655. },
  72656. set: function (newValue) {
  72657. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  72658. this._onrighttriggerchanged(newValue);
  72659. }
  72660. this._rightTrigger = newValue;
  72661. },
  72662. enumerable: true,
  72663. configurable: true
  72664. });
  72665. /**
  72666. * Defines the callback to call when a button is pressed
  72667. * @param callback defines the callback to use
  72668. */
  72669. Xbox360Pad.prototype.onbuttondown = function (callback) {
  72670. this._onbuttondown = callback;
  72671. };
  72672. /**
  72673. * Defines the callback to call when a button is released
  72674. * @param callback defines the callback to use
  72675. */
  72676. Xbox360Pad.prototype.onbuttonup = function (callback) {
  72677. this._onbuttonup = callback;
  72678. };
  72679. /**
  72680. * Defines the callback to call when a pad is pressed
  72681. * @param callback defines the callback to use
  72682. */
  72683. Xbox360Pad.prototype.ondpaddown = function (callback) {
  72684. this._ondpaddown = callback;
  72685. };
  72686. /**
  72687. * Defines the callback to call when a pad is released
  72688. * @param callback defines the callback to use
  72689. */
  72690. Xbox360Pad.prototype.ondpadup = function (callback) {
  72691. this._ondpadup = callback;
  72692. };
  72693. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  72694. if (newValue !== currentValue) {
  72695. if (newValue === 1) {
  72696. if (this._onbuttondown) {
  72697. this._onbuttondown(buttonType);
  72698. }
  72699. this.onButtonDownObservable.notifyObservers(buttonType);
  72700. }
  72701. if (newValue === 0) {
  72702. if (this._onbuttonup) {
  72703. this._onbuttonup(buttonType);
  72704. }
  72705. this.onButtonUpObservable.notifyObservers(buttonType);
  72706. }
  72707. }
  72708. return newValue;
  72709. };
  72710. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  72711. if (newValue !== currentValue) {
  72712. if (newValue === 1) {
  72713. if (this._ondpaddown) {
  72714. this._ondpaddown(buttonType);
  72715. }
  72716. this.onPadDownObservable.notifyObservers(buttonType);
  72717. }
  72718. if (newValue === 0) {
  72719. if (this._ondpadup) {
  72720. this._ondpadup(buttonType);
  72721. }
  72722. this.onPadUpObservable.notifyObservers(buttonType);
  72723. }
  72724. }
  72725. return newValue;
  72726. };
  72727. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  72728. /** Gets or sets value of A button */
  72729. get: function () {
  72730. return this._buttonA;
  72731. },
  72732. set: function (value) {
  72733. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  72734. },
  72735. enumerable: true,
  72736. configurable: true
  72737. });
  72738. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  72739. /** Gets or sets value of B button */
  72740. get: function () {
  72741. return this._buttonB;
  72742. },
  72743. set: function (value) {
  72744. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  72745. },
  72746. enumerable: true,
  72747. configurable: true
  72748. });
  72749. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  72750. /** Gets or sets value of X button */
  72751. get: function () {
  72752. return this._buttonX;
  72753. },
  72754. set: function (value) {
  72755. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  72756. },
  72757. enumerable: true,
  72758. configurable: true
  72759. });
  72760. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  72761. /** Gets or sets value of Y button */
  72762. get: function () {
  72763. return this._buttonY;
  72764. },
  72765. set: function (value) {
  72766. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  72767. },
  72768. enumerable: true,
  72769. configurable: true
  72770. });
  72771. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  72772. /** Gets or sets value of Start button */
  72773. get: function () {
  72774. return this._buttonStart;
  72775. },
  72776. set: function (value) {
  72777. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  72778. },
  72779. enumerable: true,
  72780. configurable: true
  72781. });
  72782. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  72783. /** Gets or sets value of Back button */
  72784. get: function () {
  72785. return this._buttonBack;
  72786. },
  72787. set: function (value) {
  72788. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  72789. },
  72790. enumerable: true,
  72791. configurable: true
  72792. });
  72793. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  72794. /** Gets or sets value of Left button */
  72795. get: function () {
  72796. return this._buttonLB;
  72797. },
  72798. set: function (value) {
  72799. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  72800. },
  72801. enumerable: true,
  72802. configurable: true
  72803. });
  72804. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  72805. /** Gets or sets value of Right button */
  72806. get: function () {
  72807. return this._buttonRB;
  72808. },
  72809. set: function (value) {
  72810. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  72811. },
  72812. enumerable: true,
  72813. configurable: true
  72814. });
  72815. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  72816. /** Gets or sets value of left stick */
  72817. get: function () {
  72818. return this._buttonLeftStick;
  72819. },
  72820. set: function (value) {
  72821. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  72822. },
  72823. enumerable: true,
  72824. configurable: true
  72825. });
  72826. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  72827. /** Gets or sets value of right stick */
  72828. get: function () {
  72829. return this._buttonRightStick;
  72830. },
  72831. set: function (value) {
  72832. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  72833. },
  72834. enumerable: true,
  72835. configurable: true
  72836. });
  72837. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  72838. /** Gets or sets value of DPad up */
  72839. get: function () {
  72840. return this._dPadUp;
  72841. },
  72842. set: function (value) {
  72843. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  72844. },
  72845. enumerable: true,
  72846. configurable: true
  72847. });
  72848. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  72849. /** Gets or sets value of DPad down */
  72850. get: function () {
  72851. return this._dPadDown;
  72852. },
  72853. set: function (value) {
  72854. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  72855. },
  72856. enumerable: true,
  72857. configurable: true
  72858. });
  72859. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  72860. /** Gets or sets value of DPad left */
  72861. get: function () {
  72862. return this._dPadLeft;
  72863. },
  72864. set: function (value) {
  72865. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  72866. },
  72867. enumerable: true,
  72868. configurable: true
  72869. });
  72870. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  72871. /** Gets or sets value of DPad right */
  72872. get: function () {
  72873. return this._dPadRight;
  72874. },
  72875. set: function (value) {
  72876. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  72877. },
  72878. enumerable: true,
  72879. configurable: true
  72880. });
  72881. /**
  72882. * Force the gamepad to synchronize with device values
  72883. */
  72884. Xbox360Pad.prototype.update = function () {
  72885. _super.prototype.update.call(this);
  72886. if (this._isXboxOnePad) {
  72887. this.buttonA = this.browserGamepad.buttons[0].value;
  72888. this.buttonB = this.browserGamepad.buttons[1].value;
  72889. this.buttonX = this.browserGamepad.buttons[2].value;
  72890. this.buttonY = this.browserGamepad.buttons[3].value;
  72891. this.buttonLB = this.browserGamepad.buttons[4].value;
  72892. this.buttonRB = this.browserGamepad.buttons[5].value;
  72893. this.leftTrigger = this.browserGamepad.axes[2];
  72894. this.rightTrigger = this.browserGamepad.axes[5];
  72895. this.buttonBack = this.browserGamepad.buttons[9].value;
  72896. this.buttonStart = this.browserGamepad.buttons[8].value;
  72897. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  72898. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  72899. this.dPadUp = this.browserGamepad.buttons[11].value;
  72900. this.dPadDown = this.browserGamepad.buttons[12].value;
  72901. this.dPadLeft = this.browserGamepad.buttons[13].value;
  72902. this.dPadRight = this.browserGamepad.buttons[14].value;
  72903. }
  72904. else {
  72905. this.buttonA = this.browserGamepad.buttons[0].value;
  72906. this.buttonB = this.browserGamepad.buttons[1].value;
  72907. this.buttonX = this.browserGamepad.buttons[2].value;
  72908. this.buttonY = this.browserGamepad.buttons[3].value;
  72909. this.buttonLB = this.browserGamepad.buttons[4].value;
  72910. this.buttonRB = this.browserGamepad.buttons[5].value;
  72911. this.leftTrigger = this.browserGamepad.buttons[6].value;
  72912. this.rightTrigger = this.browserGamepad.buttons[7].value;
  72913. this.buttonBack = this.browserGamepad.buttons[8].value;
  72914. this.buttonStart = this.browserGamepad.buttons[9].value;
  72915. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  72916. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  72917. this.dPadUp = this.browserGamepad.buttons[12].value;
  72918. this.dPadDown = this.browserGamepad.buttons[13].value;
  72919. this.dPadLeft = this.browserGamepad.buttons[14].value;
  72920. this.dPadRight = this.browserGamepad.buttons[15].value;
  72921. }
  72922. };
  72923. Xbox360Pad.prototype.dispose = function () {
  72924. _super.prototype.dispose.call(this);
  72925. this.onButtonDownObservable.clear();
  72926. this.onButtonUpObservable.clear();
  72927. this.onPadDownObservable.clear();
  72928. this.onPadUpObservable.clear();
  72929. };
  72930. return Xbox360Pad;
  72931. }(BABYLON.Gamepad));
  72932. BABYLON.Xbox360Pad = Xbox360Pad;
  72933. })(BABYLON || (BABYLON = {}));
  72934. //# sourceMappingURL=babylon.xboxGamepad.js.map
  72935. var BABYLON;
  72936. (function (BABYLON) {
  72937. /**
  72938. * Defines the types of pose enabled controllers that are supported
  72939. */
  72940. var PoseEnabledControllerType;
  72941. (function (PoseEnabledControllerType) {
  72942. /**
  72943. * HTC Vive
  72944. */
  72945. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  72946. /**
  72947. * Oculus Rift
  72948. */
  72949. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  72950. /**
  72951. * Windows mixed reality
  72952. */
  72953. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  72954. /**
  72955. * Samsung gear VR
  72956. */
  72957. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  72958. /**
  72959. * Google Daydream
  72960. */
  72961. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  72962. /**
  72963. * Generic
  72964. */
  72965. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  72966. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  72967. /**
  72968. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72969. */
  72970. var PoseEnabledControllerHelper = /** @class */ (function () {
  72971. function PoseEnabledControllerHelper() {
  72972. }
  72973. /**
  72974. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72975. * @param vrGamepad the gamepad to initialized
  72976. * @returns a vr controller of the type the gamepad identified as
  72977. */
  72978. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  72979. // Oculus Touch
  72980. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  72981. return new BABYLON.OculusTouchController(vrGamepad);
  72982. }
  72983. // Windows Mixed Reality controllers
  72984. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  72985. return new BABYLON.WindowsMotionController(vrGamepad);
  72986. }
  72987. // HTC Vive
  72988. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  72989. return new BABYLON.ViveController(vrGamepad);
  72990. }
  72991. // Samsung/Oculus Gear VR or Oculus Go
  72992. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  72993. return new BABYLON.GearVRController(vrGamepad);
  72994. }
  72995. // Google Daydream
  72996. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  72997. return new BABYLON.DaydreamController(vrGamepad);
  72998. }
  72999. // Generic
  73000. else {
  73001. return new BABYLON.GenericController(vrGamepad);
  73002. }
  73003. };
  73004. return PoseEnabledControllerHelper;
  73005. }());
  73006. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  73007. /**
  73008. * Defines the PoseEnabledController object that contains state of a vr capable controller
  73009. */
  73010. var PoseEnabledController = /** @class */ (function (_super) {
  73011. __extends(PoseEnabledController, _super);
  73012. /**
  73013. * Creates a new PoseEnabledController from a gamepad
  73014. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  73015. */
  73016. function PoseEnabledController(browserGamepad) {
  73017. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  73018. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  73019. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  73020. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  73021. /**
  73022. * The device position in babylon space
  73023. */
  73024. _this.devicePosition = BABYLON.Vector3.Zero();
  73025. /**
  73026. * The device rotation in babylon space
  73027. */
  73028. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  73029. /**
  73030. * The scale factor of the device in babylon space
  73031. */
  73032. _this.deviceScaleFactor = 1;
  73033. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  73034. /**
  73035. * Internal, matrix used to convert room space to babylon space
  73036. */
  73037. _this._deviceToWorld = BABYLON.Matrix.Identity();
  73038. /**
  73039. * Node to be used when casting a ray from the controller
  73040. */
  73041. _this._pointingPoseNode = null;
  73042. _this._workingMatrix = BABYLON.Matrix.Identity();
  73043. /**
  73044. * @hidden
  73045. */
  73046. _this._meshAttachedObservable = new BABYLON.Observable();
  73047. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  73048. _this.controllerType = PoseEnabledControllerType.GENERIC;
  73049. _this.position = BABYLON.Vector3.Zero();
  73050. _this.rotationQuaternion = new BABYLON.Quaternion();
  73051. _this._calculatedPosition = BABYLON.Vector3.Zero();
  73052. _this._calculatedRotation = new BABYLON.Quaternion();
  73053. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  73054. return _this;
  73055. }
  73056. /**
  73057. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  73058. */
  73059. PoseEnabledController.prototype.update = function () {
  73060. _super.prototype.update.call(this);
  73061. this._updatePoseAndMesh();
  73062. };
  73063. /**
  73064. * Updates only the pose device and mesh without doing any button event checking
  73065. */
  73066. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  73067. var pose = this.browserGamepad.pose;
  73068. this.updateFromDevice(pose);
  73069. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  73070. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  73071. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  73072. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  73073. if (this._mesh) {
  73074. this._mesh.position.copyFrom(this.devicePosition);
  73075. if (this._mesh.rotationQuaternion) {
  73076. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  73077. }
  73078. }
  73079. };
  73080. /**
  73081. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  73082. * @param poseData raw pose fromthe device
  73083. */
  73084. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  73085. if (poseData) {
  73086. this.rawPose = poseData;
  73087. if (poseData.position) {
  73088. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  73089. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  73090. this._deviceRoomPosition.z *= -1;
  73091. }
  73092. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  73093. this._calculatedPosition.addInPlace(this.position);
  73094. }
  73095. var pose = this.rawPose;
  73096. if (poseData.orientation && pose.orientation) {
  73097. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  73098. if (this._mesh) {
  73099. if (this._mesh.getScene().useRightHandedSystem) {
  73100. this._deviceRoomRotationQuaternion.z *= -1;
  73101. this._deviceRoomRotationQuaternion.w *= -1;
  73102. }
  73103. else {
  73104. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  73105. }
  73106. }
  73107. // if the camera is set, rotate to the camera's rotation
  73108. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  73109. }
  73110. }
  73111. };
  73112. /**
  73113. * Attaches a mesh to the controller
  73114. * @param mesh the mesh to be attached
  73115. */
  73116. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  73117. if (this._mesh) {
  73118. this._mesh.parent = null;
  73119. }
  73120. this._mesh = mesh;
  73121. if (this._poseControlledCamera) {
  73122. this._mesh.parent = this._poseControlledCamera;
  73123. }
  73124. if (!this._mesh.rotationQuaternion) {
  73125. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  73126. }
  73127. // 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
  73128. this._updatePoseAndMesh();
  73129. if (this._pointingPoseNode) {
  73130. var parents = [];
  73131. var obj = this._pointingPoseNode;
  73132. while (obj.parent) {
  73133. parents.push(obj.parent);
  73134. obj = obj.parent;
  73135. }
  73136. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  73137. }
  73138. this._meshAttachedObservable.notifyObservers(mesh);
  73139. };
  73140. /**
  73141. * Attaches the controllers mesh to a camera
  73142. * @param camera the camera the mesh should be attached to
  73143. */
  73144. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  73145. this._poseControlledCamera = camera;
  73146. if (this._mesh) {
  73147. this._mesh.parent = this._poseControlledCamera;
  73148. }
  73149. };
  73150. /**
  73151. * Disposes of the controller
  73152. */
  73153. PoseEnabledController.prototype.dispose = function () {
  73154. if (this._mesh) {
  73155. this._mesh.dispose();
  73156. }
  73157. this._mesh = null;
  73158. _super.prototype.dispose.call(this);
  73159. };
  73160. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  73161. /**
  73162. * The mesh that is attached to the controller
  73163. */
  73164. get: function () {
  73165. return this._mesh;
  73166. },
  73167. enumerable: true,
  73168. configurable: true
  73169. });
  73170. /**
  73171. * Gets the ray of the controller in the direction the controller is pointing
  73172. * @param length the length the resulting ray should be
  73173. * @returns a ray in the direction the controller is pointing
  73174. */
  73175. PoseEnabledController.prototype.getForwardRay = function (length) {
  73176. if (length === void 0) { length = 100; }
  73177. if (!this.mesh) {
  73178. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  73179. }
  73180. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  73181. var origin = m.getTranslation();
  73182. var forward = new BABYLON.Vector3(0, 0, -1);
  73183. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73184. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73185. return new BABYLON.Ray(origin, direction, length);
  73186. };
  73187. /**
  73188. * Name of the child mesh that can be used to cast a ray from the controller
  73189. */
  73190. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  73191. return PoseEnabledController;
  73192. }(BABYLON.Gamepad));
  73193. BABYLON.PoseEnabledController = PoseEnabledController;
  73194. })(BABYLON || (BABYLON = {}));
  73195. //# sourceMappingURL=babylon.poseEnabledController.js.map
  73196. var BABYLON;
  73197. (function (BABYLON) {
  73198. /**
  73199. * Defines the WebVRController object that represents controllers tracked in 3D space
  73200. */
  73201. var WebVRController = /** @class */ (function (_super) {
  73202. __extends(WebVRController, _super);
  73203. /**
  73204. * Creates a new WebVRController from a gamepad
  73205. * @param vrGamepad the gamepad that the WebVRController should be created from
  73206. */
  73207. function WebVRController(vrGamepad) {
  73208. var _this = _super.call(this, vrGamepad) || this;
  73209. // Observables
  73210. /**
  73211. * Fired when the trigger state has changed
  73212. */
  73213. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  73214. /**
  73215. * Fired when the main button state has changed
  73216. */
  73217. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  73218. /**
  73219. * Fired when the secondary button state has changed
  73220. */
  73221. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  73222. /**
  73223. * Fired when the pad state has changed
  73224. */
  73225. _this.onPadStateChangedObservable = new BABYLON.Observable();
  73226. /**
  73227. * Fired when controllers stick values have changed
  73228. */
  73229. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  73230. /**
  73231. * X and Y axis corrisponding to the controllers joystick
  73232. */
  73233. _this.pad = { x: 0, y: 0 };
  73234. // avoid GC, store state in a tmp object
  73235. _this._changes = {
  73236. pressChanged: false,
  73237. touchChanged: false,
  73238. valueChanged: false,
  73239. changed: false
  73240. };
  73241. _this._buttons = new Array(vrGamepad.buttons.length);
  73242. _this.hand = vrGamepad.hand;
  73243. return _this;
  73244. }
  73245. /**
  73246. * Fired when a controller button's state has changed
  73247. * @param callback the callback containing the button that was modified
  73248. */
  73249. WebVRController.prototype.onButtonStateChange = function (callback) {
  73250. this._onButtonStateChange = callback;
  73251. };
  73252. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  73253. /**
  73254. * The default controller model for the controller
  73255. */
  73256. get: function () {
  73257. return this._defaultModel;
  73258. },
  73259. enumerable: true,
  73260. configurable: true
  73261. });
  73262. /**
  73263. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  73264. */
  73265. WebVRController.prototype.update = function () {
  73266. _super.prototype.update.call(this);
  73267. for (var index = 0; index < this._buttons.length; index++) {
  73268. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  73269. }
  73270. ;
  73271. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  73272. this.pad.x = this.leftStick.x;
  73273. this.pad.y = this.leftStick.y;
  73274. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  73275. }
  73276. };
  73277. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  73278. if (!newState) {
  73279. newState = {
  73280. pressed: false,
  73281. touched: false,
  73282. value: 0
  73283. };
  73284. }
  73285. if (!currentState) {
  73286. this._buttons[buttonIndex] = {
  73287. pressed: newState.pressed,
  73288. touched: newState.touched,
  73289. value: newState.value
  73290. };
  73291. return;
  73292. }
  73293. this._checkChanges(newState, currentState);
  73294. if (this._changes.changed) {
  73295. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  73296. this._handleButtonChange(buttonIndex, newState, this._changes);
  73297. }
  73298. this._buttons[buttonIndex].pressed = newState.pressed;
  73299. this._buttons[buttonIndex].touched = newState.touched;
  73300. // oculus triggers are never 0, thou not touched.
  73301. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  73302. };
  73303. WebVRController.prototype._checkChanges = function (newState, currentState) {
  73304. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  73305. this._changes.touchChanged = newState.touched !== currentState.touched;
  73306. this._changes.valueChanged = newState.value !== currentState.value;
  73307. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  73308. return this._changes;
  73309. };
  73310. /**
  73311. * Disposes of th webVRCOntroller
  73312. */
  73313. WebVRController.prototype.dispose = function () {
  73314. _super.prototype.dispose.call(this);
  73315. this.onTriggerStateChangedObservable.clear();
  73316. this.onMainButtonStateChangedObservable.clear();
  73317. this.onSecondaryButtonStateChangedObservable.clear();
  73318. this.onPadStateChangedObservable.clear();
  73319. this.onPadValuesChangedObservable.clear();
  73320. };
  73321. return WebVRController;
  73322. }(BABYLON.PoseEnabledController));
  73323. BABYLON.WebVRController = WebVRController;
  73324. })(BABYLON || (BABYLON = {}));
  73325. //# sourceMappingURL=babylon.webVRController.js.map
  73326. var BABYLON;
  73327. (function (BABYLON) {
  73328. /**
  73329. * Oculus Touch Controller
  73330. */
  73331. var OculusTouchController = /** @class */ (function (_super) {
  73332. __extends(OculusTouchController, _super);
  73333. /**
  73334. * Creates a new OculusTouchController from a gamepad
  73335. * @param vrGamepad the gamepad that the controller should be created from
  73336. */
  73337. function OculusTouchController(vrGamepad) {
  73338. var _this = _super.call(this, vrGamepad) || this;
  73339. /**
  73340. * Fired when the secondary trigger on this controller is modified
  73341. */
  73342. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  73343. /**
  73344. * Fired when the thumb rest on this controller is modified
  73345. */
  73346. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  73347. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  73348. return _this;
  73349. }
  73350. /**
  73351. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73352. * @param scene scene in which to add meshes
  73353. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73354. */
  73355. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73356. var _this = this;
  73357. var meshName;
  73358. // Hand
  73359. if (this.hand === 'left') {
  73360. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  73361. }
  73362. else { // Right is the default if no hand is specified
  73363. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  73364. }
  73365. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  73366. /*
  73367. Parent Mesh name: oculus_touch_left
  73368. - body
  73369. - trigger
  73370. - thumbstick
  73371. - grip
  73372. - button_y
  73373. - button_x
  73374. - button_enter
  73375. */
  73376. _this._defaultModel = newMeshes[1];
  73377. _this.attachToMesh(_this._defaultModel);
  73378. if (meshLoaded) {
  73379. meshLoaded(_this._defaultModel);
  73380. }
  73381. });
  73382. };
  73383. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  73384. /**
  73385. * Fired when the A button on this controller is modified
  73386. */
  73387. get: function () {
  73388. if (this.hand === 'right') {
  73389. return this.onMainButtonStateChangedObservable;
  73390. }
  73391. else {
  73392. throw new Error('No A button on left hand');
  73393. }
  73394. },
  73395. enumerable: true,
  73396. configurable: true
  73397. });
  73398. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  73399. /**
  73400. * Fired when the B button on this controller is modified
  73401. */
  73402. get: function () {
  73403. if (this.hand === 'right') {
  73404. return this.onSecondaryButtonStateChangedObservable;
  73405. }
  73406. else {
  73407. throw new Error('No B button on left hand');
  73408. }
  73409. },
  73410. enumerable: true,
  73411. configurable: true
  73412. });
  73413. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  73414. /**
  73415. * Fired when the X button on this controller is modified
  73416. */
  73417. get: function () {
  73418. if (this.hand === 'left') {
  73419. return this.onMainButtonStateChangedObservable;
  73420. }
  73421. else {
  73422. throw new Error('No X button on right hand');
  73423. }
  73424. },
  73425. enumerable: true,
  73426. configurable: true
  73427. });
  73428. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  73429. /**
  73430. * Fired when the Y button on this controller is modified
  73431. */
  73432. get: function () {
  73433. if (this.hand === 'left') {
  73434. return this.onSecondaryButtonStateChangedObservable;
  73435. }
  73436. else {
  73437. throw new Error('No Y button on right hand');
  73438. }
  73439. },
  73440. enumerable: true,
  73441. configurable: true
  73442. });
  73443. /**
  73444. * Called once for each button that changed state since the last frame
  73445. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  73446. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  73447. * 2) secondary trigger (same)
  73448. * 3) A (right) X (left), touch, pressed = value
  73449. * 4) B / Y
  73450. * 5) thumb rest
  73451. * @param buttonIdx Which button index changed
  73452. * @param state New state of the button
  73453. * @param changes Which properties on the state changed since last frame
  73454. */
  73455. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73456. var notifyObject = state; //{ state: state, changes: changes };
  73457. var triggerDirection = this.hand === 'right' ? -1 : 1;
  73458. switch (buttonIdx) {
  73459. case 0:
  73460. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73461. return;
  73462. case 1: // index trigger
  73463. if (this._defaultModel) {
  73464. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  73465. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  73466. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  73467. }
  73468. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73469. return;
  73470. case 2: // secondary trigger
  73471. if (this._defaultModel) {
  73472. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  73473. }
  73474. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  73475. return;
  73476. case 3:
  73477. if (this._defaultModel) {
  73478. if (notifyObject.pressed) {
  73479. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  73480. }
  73481. else {
  73482. (this._defaultModel.getChildren()[1]).position.y = 0;
  73483. }
  73484. }
  73485. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73486. return;
  73487. case 4:
  73488. if (this._defaultModel) {
  73489. if (notifyObject.pressed) {
  73490. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73491. }
  73492. else {
  73493. (this._defaultModel.getChildren()[2]).position.y = 0;
  73494. }
  73495. }
  73496. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73497. return;
  73498. case 5:
  73499. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  73500. return;
  73501. }
  73502. };
  73503. /**
  73504. * Base Url for the controller model.
  73505. */
  73506. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  73507. /**
  73508. * File name for the left controller model.
  73509. */
  73510. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  73511. /**
  73512. * File name for the right controller model.
  73513. */
  73514. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  73515. return OculusTouchController;
  73516. }(BABYLON.WebVRController));
  73517. BABYLON.OculusTouchController = OculusTouchController;
  73518. })(BABYLON || (BABYLON = {}));
  73519. //# sourceMappingURL=babylon.oculusTouchController.js.map
  73520. var BABYLON;
  73521. (function (BABYLON) {
  73522. /**
  73523. * Vive Controller
  73524. */
  73525. var ViveController = /** @class */ (function (_super) {
  73526. __extends(ViveController, _super);
  73527. /**
  73528. * Creates a new ViveController from a gamepad
  73529. * @param vrGamepad the gamepad that the controller should be created from
  73530. */
  73531. function ViveController(vrGamepad) {
  73532. var _this = _super.call(this, vrGamepad) || this;
  73533. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  73534. _this._invertLeftStickY = true;
  73535. return _this;
  73536. }
  73537. /**
  73538. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73539. * @param scene scene in which to add meshes
  73540. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73541. */
  73542. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73543. var _this = this;
  73544. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  73545. /*
  73546. Parent Mesh name: ViveWand
  73547. - body
  73548. - r_gripper
  73549. - l_gripper
  73550. - menu_button
  73551. - system_button
  73552. - trackpad
  73553. - trigger
  73554. - LED
  73555. */
  73556. _this._defaultModel = newMeshes[1];
  73557. _this.attachToMesh(_this._defaultModel);
  73558. if (meshLoaded) {
  73559. meshLoaded(_this._defaultModel);
  73560. }
  73561. });
  73562. };
  73563. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  73564. /**
  73565. * Fired when the left button on this controller is modified
  73566. */
  73567. get: function () {
  73568. return this.onMainButtonStateChangedObservable;
  73569. },
  73570. enumerable: true,
  73571. configurable: true
  73572. });
  73573. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  73574. /**
  73575. * Fired when the right button on this controller is modified
  73576. */
  73577. get: function () {
  73578. return this.onMainButtonStateChangedObservable;
  73579. },
  73580. enumerable: true,
  73581. configurable: true
  73582. });
  73583. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  73584. /**
  73585. * Fired when the menu button on this controller is modified
  73586. */
  73587. get: function () {
  73588. return this.onSecondaryButtonStateChangedObservable;
  73589. },
  73590. enumerable: true,
  73591. configurable: true
  73592. });
  73593. /**
  73594. * Called once for each button that changed state since the last frame
  73595. * Vive mapping:
  73596. * 0: touchpad
  73597. * 1: trigger
  73598. * 2: left AND right buttons
  73599. * 3: menu button
  73600. * @param buttonIdx Which button index changed
  73601. * @param state New state of the button
  73602. * @param changes Which properties on the state changed since last frame
  73603. */
  73604. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73605. var notifyObject = state; //{ state: state, changes: changes };
  73606. switch (buttonIdx) {
  73607. case 0:
  73608. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73609. return;
  73610. case 1: // index trigger
  73611. if (this._defaultModel) {
  73612. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  73613. }
  73614. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73615. return;
  73616. case 2: // left AND right button
  73617. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73618. return;
  73619. case 3:
  73620. if (this._defaultModel) {
  73621. if (notifyObject.pressed) {
  73622. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73623. }
  73624. else {
  73625. (this._defaultModel.getChildren()[2]).position.y = 0;
  73626. }
  73627. }
  73628. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73629. return;
  73630. }
  73631. };
  73632. /**
  73633. * Base Url for the controller model.
  73634. */
  73635. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  73636. /**
  73637. * File name for the controller model.
  73638. */
  73639. ViveController.MODEL_FILENAME = 'wand.babylon';
  73640. return ViveController;
  73641. }(BABYLON.WebVRController));
  73642. BABYLON.ViveController = ViveController;
  73643. })(BABYLON || (BABYLON = {}));
  73644. //# sourceMappingURL=babylon.viveController.js.map
  73645. var BABYLON;
  73646. (function (BABYLON) {
  73647. /**
  73648. * Generic Controller
  73649. */
  73650. var GenericController = /** @class */ (function (_super) {
  73651. __extends(GenericController, _super);
  73652. /**
  73653. * Creates a new GenericController from a gamepad
  73654. * @param vrGamepad the gamepad that the controller should be created from
  73655. */
  73656. function GenericController(vrGamepad) {
  73657. return _super.call(this, vrGamepad) || this;
  73658. }
  73659. /**
  73660. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73661. * @param scene scene in which to add meshes
  73662. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73663. */
  73664. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73665. var _this = this;
  73666. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  73667. _this._defaultModel = newMeshes[1];
  73668. _this.attachToMesh(_this._defaultModel);
  73669. if (meshLoaded) {
  73670. meshLoaded(_this._defaultModel);
  73671. }
  73672. });
  73673. };
  73674. /**
  73675. * Called once for each button that changed state since the last frame
  73676. * @param buttonIdx Which button index changed
  73677. * @param state New state of the button
  73678. * @param changes Which properties on the state changed since last frame
  73679. */
  73680. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73681. console.log("Button id: " + buttonIdx + "state: ");
  73682. console.dir(state);
  73683. };
  73684. /**
  73685. * Base Url for the controller model.
  73686. */
  73687. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73688. /**
  73689. * File name for the controller model.
  73690. */
  73691. GenericController.MODEL_FILENAME = 'generic.babylon';
  73692. return GenericController;
  73693. }(BABYLON.WebVRController));
  73694. BABYLON.GenericController = GenericController;
  73695. })(BABYLON || (BABYLON = {}));
  73696. //# sourceMappingURL=babylon.genericController.js.map
  73697. var BABYLON;
  73698. (function (BABYLON) {
  73699. /**
  73700. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  73701. */
  73702. var LoadedMeshInfo = /** @class */ (function () {
  73703. function LoadedMeshInfo() {
  73704. /**
  73705. * Map of the button meshes contained in the controller
  73706. */
  73707. this.buttonMeshes = {};
  73708. /**
  73709. * Map of the axis meshes contained in the controller
  73710. */
  73711. this.axisMeshes = {};
  73712. }
  73713. return LoadedMeshInfo;
  73714. }());
  73715. /**
  73716. * Defines the WindowsMotionController object that the state of the windows motion controller
  73717. */
  73718. var WindowsMotionController = /** @class */ (function (_super) {
  73719. __extends(WindowsMotionController, _super);
  73720. /**
  73721. * Creates a new WindowsMotionController from a gamepad
  73722. * @param vrGamepad the gamepad that the controller should be created from
  73723. */
  73724. function WindowsMotionController(vrGamepad) {
  73725. var _this = _super.call(this, vrGamepad) || this;
  73726. _this._mapping = {
  73727. // Semantic button names
  73728. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  73729. // A mapping of the button name to glTF model node name
  73730. // that should be transformed by button value.
  73731. buttonMeshNames: {
  73732. 'trigger': 'SELECT',
  73733. 'menu': 'MENU',
  73734. 'grip': 'GRASP',
  73735. 'thumbstick': 'THUMBSTICK_PRESS',
  73736. 'trackpad': 'TOUCHPAD_PRESS'
  73737. },
  73738. // This mapping is used to translate from the Motion Controller to Babylon semantics
  73739. buttonObservableNames: {
  73740. 'trigger': 'onTriggerStateChangedObservable',
  73741. 'menu': 'onSecondaryButtonStateChangedObservable',
  73742. 'grip': 'onMainButtonStateChangedObservable',
  73743. 'thumbstick': 'onPadStateChangedObservable',
  73744. 'trackpad': 'onTrackpadChangedObservable'
  73745. },
  73746. // A mapping of the axis name to glTF model node name
  73747. // that should be transformed by axis value.
  73748. // This array mirrors the browserGamepad.axes array, such that
  73749. // the mesh corresponding to axis 0 is in this array index 0.
  73750. axisMeshNames: [
  73751. 'THUMBSTICK_X',
  73752. 'THUMBSTICK_Y',
  73753. 'TOUCHPAD_TOUCH_X',
  73754. 'TOUCHPAD_TOUCH_Y'
  73755. ],
  73756. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  73757. };
  73758. /**
  73759. * Fired when the trackpad on this controller is clicked
  73760. */
  73761. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  73762. /**
  73763. * Fired when the trackpad on this controller is modified
  73764. */
  73765. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  73766. /**
  73767. * The current x and y values of this controller's trackpad
  73768. */
  73769. _this.trackpad = { x: 0, y: 0 };
  73770. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  73771. _this._loadedMeshInfo = null;
  73772. return _this;
  73773. }
  73774. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  73775. /**
  73776. * Fired when the trigger on this controller is modified
  73777. */
  73778. get: function () {
  73779. return this.onTriggerStateChangedObservable;
  73780. },
  73781. enumerable: true,
  73782. configurable: true
  73783. });
  73784. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  73785. /**
  73786. * Fired when the menu button on this controller is modified
  73787. */
  73788. get: function () {
  73789. return this.onSecondaryButtonStateChangedObservable;
  73790. },
  73791. enumerable: true,
  73792. configurable: true
  73793. });
  73794. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  73795. /**
  73796. * Fired when the grip button on this controller is modified
  73797. */
  73798. get: function () {
  73799. return this.onMainButtonStateChangedObservable;
  73800. },
  73801. enumerable: true,
  73802. configurable: true
  73803. });
  73804. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  73805. /**
  73806. * Fired when the thumbstick button on this controller is modified
  73807. */
  73808. get: function () {
  73809. return this.onPadStateChangedObservable;
  73810. },
  73811. enumerable: true,
  73812. configurable: true
  73813. });
  73814. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  73815. /**
  73816. * Fired when the touchpad button on this controller is modified
  73817. */
  73818. get: function () {
  73819. return this.onTrackpadChangedObservable;
  73820. },
  73821. enumerable: true,
  73822. configurable: true
  73823. });
  73824. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  73825. /**
  73826. * Fired when the touchpad values on this controller are modified
  73827. */
  73828. get: function () {
  73829. return this.onTrackpadValuesChangedObservable;
  73830. },
  73831. enumerable: true,
  73832. configurable: true
  73833. });
  73834. WindowsMotionController.prototype._updateTrackpad = function () {
  73835. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  73836. this.trackpad.x = this.browserGamepad["axes"][2];
  73837. this.trackpad.y = this.browserGamepad["axes"][3];
  73838. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  73839. }
  73840. };
  73841. /**
  73842. * Called once per frame by the engine.
  73843. */
  73844. WindowsMotionController.prototype.update = function () {
  73845. _super.prototype.update.call(this);
  73846. if (this.browserGamepad.axes) {
  73847. this._updateTrackpad();
  73848. // Only need to animate axes if there is a loaded mesh
  73849. if (this._loadedMeshInfo) {
  73850. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  73851. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  73852. }
  73853. }
  73854. }
  73855. };
  73856. /**
  73857. * Called once for each button that changed state since the last frame
  73858. * @param buttonIdx Which button index changed
  73859. * @param state New state of the button
  73860. * @param changes Which properties on the state changed since last frame
  73861. */
  73862. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73863. var buttonName = this._mapping.buttons[buttonIdx];
  73864. if (!buttonName) {
  73865. return;
  73866. }
  73867. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  73868. this._updateTrackpad();
  73869. // Only emit events for buttons that we know how to map from index to name
  73870. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  73871. if (observable) {
  73872. observable.notifyObservers(state);
  73873. }
  73874. this._lerpButtonTransform(buttonName, state.value);
  73875. };
  73876. /**
  73877. * Moves the buttons on the controller mesh based on their current state
  73878. * @param buttonName the name of the button to move
  73879. * @param buttonValue the value of the button which determines the buttons new position
  73880. */
  73881. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  73882. // If there is no loaded mesh, there is nothing to transform.
  73883. if (!this._loadedMeshInfo) {
  73884. return;
  73885. }
  73886. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  73887. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73888. return;
  73889. }
  73890. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  73891. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  73892. };
  73893. /**
  73894. * Moves the axis on the controller mesh based on its current state
  73895. * @param axis the index of the axis
  73896. * @param axisValue the value of the axis which determines the meshes new position
  73897. * @hidden
  73898. */
  73899. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  73900. if (!this._loadedMeshInfo) {
  73901. return;
  73902. }
  73903. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  73904. if (!meshInfo) {
  73905. return;
  73906. }
  73907. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73908. return;
  73909. }
  73910. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  73911. var lerpValue = axisValue * 0.5 + 0.5;
  73912. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  73913. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  73914. };
  73915. /**
  73916. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73917. * @param scene scene in which to add meshes
  73918. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73919. */
  73920. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  73921. var _this = this;
  73922. if (forceDefault === void 0) { forceDefault = false; }
  73923. var path;
  73924. var filename;
  73925. // Checking if GLB loader is present
  73926. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  73927. // Determine the device specific folder based on the ID suffix
  73928. var device = 'default';
  73929. if (this.id && !forceDefault) {
  73930. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  73931. device = ((match && match[0]) || device);
  73932. }
  73933. // Hand
  73934. if (this.hand === 'left') {
  73935. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  73936. }
  73937. else { // Right is the default if no hand is specified
  73938. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  73939. }
  73940. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  73941. }
  73942. else {
  73943. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  73944. path = BABYLON.GenericController.MODEL_BASE_URL;
  73945. filename = BABYLON.GenericController.MODEL_FILENAME;
  73946. }
  73947. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  73948. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  73949. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  73950. if (!_this._loadedMeshInfo) {
  73951. return;
  73952. }
  73953. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  73954. _this.attachToMesh(_this._defaultModel);
  73955. if (meshLoaded) {
  73956. meshLoaded(_this._defaultModel);
  73957. }
  73958. }, null, function (scene, message) {
  73959. BABYLON.Tools.Log(message);
  73960. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  73961. if (!forceDefault) {
  73962. _this.initControllerMesh(scene, meshLoaded, true);
  73963. }
  73964. });
  73965. };
  73966. /**
  73967. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  73968. * can be transformed by button presses and axes values, based on this._mapping.
  73969. *
  73970. * @param scene scene in which the meshes exist
  73971. * @param meshes list of meshes that make up the controller model to process
  73972. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  73973. */
  73974. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  73975. var loadedMeshInfo = null;
  73976. // Create a new mesh to contain the glTF hierarchy
  73977. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  73978. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  73979. var childMesh = null;
  73980. for (var i = 0; i < meshes.length; i++) {
  73981. var mesh = meshes[i];
  73982. if (!mesh.parent) {
  73983. // Exclude controller meshes from picking results
  73984. mesh.isPickable = false;
  73985. // Handle root node, attach to the new parentMesh
  73986. childMesh = mesh;
  73987. break;
  73988. }
  73989. }
  73990. if (childMesh) {
  73991. childMesh.setParent(parentMesh);
  73992. // Create our mesh info. Note that this method will always return non-null.
  73993. loadedMeshInfo = this.createMeshInfo(parentMesh);
  73994. }
  73995. else {
  73996. BABYLON.Tools.Warn('Could not find root node in model file.');
  73997. }
  73998. return loadedMeshInfo;
  73999. };
  74000. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  74001. var loadedMeshInfo = new LoadedMeshInfo();
  74002. var i;
  74003. loadedMeshInfo.rootNode = rootNode;
  74004. // Reset the caches
  74005. loadedMeshInfo.buttonMeshes = {};
  74006. loadedMeshInfo.axisMeshes = {};
  74007. // Button Meshes
  74008. for (i = 0; i < this._mapping.buttons.length; i++) {
  74009. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  74010. if (!buttonMeshName) {
  74011. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  74012. continue;
  74013. }
  74014. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  74015. if (!buttonMesh) {
  74016. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  74017. continue;
  74018. }
  74019. var buttonMeshInfo = {
  74020. index: i,
  74021. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  74022. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  74023. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  74024. };
  74025. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  74026. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  74027. }
  74028. else {
  74029. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  74030. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  74031. '(VALUE: ' + !!buttonMeshInfo.value +
  74032. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  74033. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  74034. ')');
  74035. }
  74036. }
  74037. // Axis Meshes
  74038. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  74039. var axisMeshName = this._mapping.axisMeshNames[i];
  74040. if (!axisMeshName) {
  74041. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  74042. continue;
  74043. }
  74044. var axisMesh = getChildByName(rootNode, axisMeshName);
  74045. if (!axisMesh) {
  74046. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  74047. continue;
  74048. }
  74049. var axisMeshInfo = {
  74050. index: i,
  74051. value: getImmediateChildByName(axisMesh, 'VALUE'),
  74052. min: getImmediateChildByName(axisMesh, 'MIN'),
  74053. max: getImmediateChildByName(axisMesh, 'MAX')
  74054. };
  74055. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  74056. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  74057. }
  74058. else {
  74059. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  74060. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  74061. '(VALUE: ' + !!axisMeshInfo.value +
  74062. ', MIN: ' + !!axisMeshInfo.min +
  74063. ', MAX:' + !!axisMeshInfo.max +
  74064. ')');
  74065. }
  74066. }
  74067. // Pointing Ray
  74068. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  74069. if (!loadedMeshInfo.pointingPoseNode) {
  74070. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  74071. }
  74072. else {
  74073. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  74074. }
  74075. return loadedMeshInfo;
  74076. // Look through all children recursively. This will return null if no mesh exists with the given name.
  74077. function getChildByName(node, name) {
  74078. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  74079. }
  74080. // Look through only immediate children. This will return null if no mesh exists with the given name.
  74081. function getImmediateChildByName(node, name) {
  74082. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  74083. }
  74084. };
  74085. /**
  74086. * Gets the ray of the controller in the direction the controller is pointing
  74087. * @param length the length the resulting ray should be
  74088. * @returns a ray in the direction the controller is pointing
  74089. */
  74090. WindowsMotionController.prototype.getForwardRay = function (length) {
  74091. if (length === void 0) { length = 100; }
  74092. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  74093. return _super.prototype.getForwardRay.call(this, length);
  74094. }
  74095. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  74096. var origin = m.getTranslation();
  74097. var forward = new BABYLON.Vector3(0, 0, -1);
  74098. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74099. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74100. return new BABYLON.Ray(origin, direction, length);
  74101. };
  74102. /**
  74103. * Disposes of the controller
  74104. */
  74105. WindowsMotionController.prototype.dispose = function () {
  74106. _super.prototype.dispose.call(this);
  74107. this.onTrackpadChangedObservable.clear();
  74108. };
  74109. /**
  74110. * The base url used to load the left and right controller models
  74111. */
  74112. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  74113. /**
  74114. * The name of the left controller model file
  74115. */
  74116. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  74117. /**
  74118. * The name of the right controller model file
  74119. */
  74120. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  74121. /**
  74122. * The controller name prefix for this controller type
  74123. */
  74124. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  74125. /**
  74126. * The controller id pattern for this controller type
  74127. */
  74128. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  74129. return WindowsMotionController;
  74130. }(BABYLON.WebVRController));
  74131. BABYLON.WindowsMotionController = WindowsMotionController;
  74132. })(BABYLON || (BABYLON = {}));
  74133. //# sourceMappingURL=babylon.windowsMotionController.js.map
  74134. var BABYLON;
  74135. (function (BABYLON) {
  74136. /**
  74137. * Gear VR Controller
  74138. */
  74139. var GearVRController = /** @class */ (function (_super) {
  74140. __extends(GearVRController, _super);
  74141. /**
  74142. * Creates a new GearVRController from a gamepad
  74143. * @param vrGamepad the gamepad that the controller should be created from
  74144. */
  74145. function GearVRController(vrGamepad) {
  74146. var _this = _super.call(this, vrGamepad) || this;
  74147. _this._maxRotationDistFromHeadset = Math.PI / 5;
  74148. _this._draggedRoomRotation = 0;
  74149. _this._tmpVector = new BABYLON.Vector3();
  74150. _this._buttonIndexToObservableNameMap = [
  74151. 'onTrackpadChangedObservable',
  74152. 'onTriggerStateChangedObservable' // Trigger
  74153. ];
  74154. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  74155. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  74156. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  74157. return _this;
  74158. }
  74159. /**
  74160. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74161. * @param poseData raw pose fromthe device
  74162. */
  74163. GearVRController.prototype.updateFromDevice = function (poseData) {
  74164. _super.prototype.updateFromDevice.call(this, poseData);
  74165. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  74166. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  74167. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  74168. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  74169. // Find the radian distance away that the headset is from the controllers rotation
  74170. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  74171. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  74172. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  74173. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  74174. this._draggedRoomRotation += rotationAmount;
  74175. // Rotate controller around headset
  74176. var sin = Math.sin(-rotationAmount);
  74177. var cos = Math.cos(-rotationAmount);
  74178. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  74179. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  74180. }
  74181. }
  74182. }
  74183. };
  74184. /**
  74185. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74186. * @param scene scene in which to add meshes
  74187. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74188. */
  74189. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74190. var _this = this;
  74191. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  74192. // Offset the controller so it will rotate around the users wrist
  74193. var mesh = new BABYLON.Mesh("", scene);
  74194. newMeshes[1].parent = mesh;
  74195. newMeshes[1].position.z = -0.15;
  74196. _this._defaultModel = mesh;
  74197. _this.attachToMesh(_this._defaultModel);
  74198. if (meshLoaded) {
  74199. meshLoaded(_this._defaultModel);
  74200. }
  74201. });
  74202. };
  74203. /**
  74204. * Called once for each button that changed state since the last frame
  74205. * @param buttonIdx Which button index changed
  74206. * @param state New state of the button
  74207. * @param changes Which properties on the state changed since last frame
  74208. */
  74209. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74210. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  74211. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  74212. // Only emit events for buttons that we know how to map from index to observable
  74213. var observable = this[observableName];
  74214. if (observable) {
  74215. observable.notifyObservers(state);
  74216. }
  74217. }
  74218. };
  74219. /**
  74220. * Base Url for the controller model.
  74221. */
  74222. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74223. /**
  74224. * File name for the controller model.
  74225. */
  74226. GearVRController.MODEL_FILENAME = 'generic.babylon';
  74227. /**
  74228. * Gamepad Id prefix used to identify this controller.
  74229. */
  74230. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  74231. return GearVRController;
  74232. }(BABYLON.WebVRController));
  74233. BABYLON.GearVRController = GearVRController;
  74234. })(BABYLON || (BABYLON = {}));
  74235. //# sourceMappingURL=babylon.gearVRController.js.map
  74236. var BABYLON;
  74237. (function (BABYLON) {
  74238. /**
  74239. * Google Daydream controller
  74240. */
  74241. var DaydreamController = /** @class */ (function (_super) {
  74242. __extends(DaydreamController, _super);
  74243. /**
  74244. * Creates a new DaydreamController from a gamepad
  74245. * @param vrGamepad the gamepad that the controller should be created from
  74246. */
  74247. function DaydreamController(vrGamepad) {
  74248. var _this = _super.call(this, vrGamepad) || this;
  74249. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  74250. return _this;
  74251. }
  74252. /**
  74253. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74254. * @param scene scene in which to add meshes
  74255. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74256. */
  74257. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74258. var _this = this;
  74259. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  74260. _this._defaultModel = newMeshes[1];
  74261. _this.attachToMesh(_this._defaultModel);
  74262. if (meshLoaded) {
  74263. meshLoaded(_this._defaultModel);
  74264. }
  74265. });
  74266. };
  74267. /**
  74268. * Called once for each button that changed state since the last frame
  74269. * @param buttonIdx Which button index changed
  74270. * @param state New state of the button
  74271. * @param changes Which properties on the state changed since last frame
  74272. */
  74273. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74274. // Daydream controller only has 1 GamepadButton (on the trackpad).
  74275. if (buttonIdx === 0) {
  74276. var observable = this.onTriggerStateChangedObservable;
  74277. if (observable) {
  74278. observable.notifyObservers(state);
  74279. }
  74280. }
  74281. else {
  74282. // If the app or home buttons are ever made available
  74283. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  74284. }
  74285. };
  74286. /**
  74287. * Base Url for the controller model.
  74288. */
  74289. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74290. /**
  74291. * File name for the controller model.
  74292. */
  74293. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  74294. /**
  74295. * Gamepad Id prefix used to identify Daydream Controller.
  74296. */
  74297. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  74298. return DaydreamController;
  74299. }(BABYLON.WebVRController));
  74300. BABYLON.DaydreamController = DaydreamController;
  74301. })(BABYLON || (BABYLON = {}));
  74302. //# sourceMappingURL=babylon.daydreamController.js.map
  74303. var BABYLON;
  74304. (function (BABYLON) {
  74305. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  74306. get: function () {
  74307. if (!this._gamepadManager) {
  74308. this._gamepadManager = new BABYLON.GamepadManager(this);
  74309. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  74310. if (!component) {
  74311. component = new GamepadSystemSceneComponent(this);
  74312. this._addComponent(component);
  74313. }
  74314. }
  74315. return this._gamepadManager;
  74316. },
  74317. enumerable: true,
  74318. configurable: true
  74319. });
  74320. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  74321. this.add(new BABYLON.FreeCameraGamepadInput());
  74322. return this;
  74323. };
  74324. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  74325. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  74326. return this;
  74327. };
  74328. /**
  74329. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  74330. */
  74331. var GamepadSystemSceneComponent = /** @class */ (function () {
  74332. /**
  74333. * Creates a new instance of the component for the given scene
  74334. * @param scene Defines the scene to register the component in
  74335. */
  74336. function GamepadSystemSceneComponent(scene) {
  74337. /**
  74338. * The component name helpfull to identify the component in the list of scene components.
  74339. */
  74340. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  74341. this.scene = scene;
  74342. }
  74343. /**
  74344. * Registers the component in a given scene
  74345. */
  74346. GamepadSystemSceneComponent.prototype.register = function () {
  74347. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  74348. };
  74349. /**
  74350. * Rebuilds the elements related to this component in case of
  74351. * context lost for instance.
  74352. */
  74353. GamepadSystemSceneComponent.prototype.rebuild = function () {
  74354. // Nothing to do for gamepads
  74355. };
  74356. /**
  74357. * Disposes the component and the associated ressources
  74358. */
  74359. GamepadSystemSceneComponent.prototype.dispose = function () {
  74360. var gamepadManager = this.scene._gamepadManager;
  74361. if (gamepadManager) {
  74362. gamepadManager.dispose();
  74363. this.scene._gamepadManager = null;
  74364. }
  74365. };
  74366. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  74367. var gamepadManager = this.scene._gamepadManager;
  74368. if (gamepadManager && gamepadManager._isMonitoring) {
  74369. gamepadManager._checkGamepadsStatus();
  74370. }
  74371. };
  74372. return GamepadSystemSceneComponent;
  74373. }());
  74374. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  74375. })(BABYLON || (BABYLON = {}));
  74376. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  74377. var BABYLON;
  74378. (function (BABYLON) {
  74379. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  74380. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  74381. });
  74382. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  74383. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  74384. });
  74385. var FollowCamera = /** @class */ (function (_super) {
  74386. __extends(FollowCamera, _super);
  74387. function FollowCamera(name, position, scene, lockedTarget) {
  74388. if (lockedTarget === void 0) { lockedTarget = null; }
  74389. var _this = _super.call(this, name, position, scene) || this;
  74390. _this.radius = 12;
  74391. _this.rotationOffset = 0;
  74392. _this.heightOffset = 4;
  74393. _this.cameraAcceleration = 0.05;
  74394. _this.maxCameraSpeed = 20;
  74395. _this.lockedTarget = lockedTarget;
  74396. return _this;
  74397. }
  74398. FollowCamera.prototype.getRadians = function (degrees) {
  74399. return degrees * Math.PI / 180;
  74400. };
  74401. FollowCamera.prototype.follow = function (cameraTarget) {
  74402. if (!cameraTarget)
  74403. return;
  74404. var yRotation;
  74405. if (cameraTarget.rotationQuaternion) {
  74406. var rotMatrix = new BABYLON.Matrix();
  74407. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  74408. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  74409. }
  74410. else {
  74411. yRotation = cameraTarget.rotation.y;
  74412. }
  74413. var radians = this.getRadians(this.rotationOffset) + yRotation;
  74414. var targetPosition = cameraTarget.getAbsolutePosition();
  74415. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  74416. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  74417. var dx = targetX - this.position.x;
  74418. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  74419. var dz = (targetZ) - this.position.z;
  74420. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  74421. var vy = dy * this.cameraAcceleration;
  74422. var vz = dz * this.cameraAcceleration * 2;
  74423. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  74424. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74425. }
  74426. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  74427. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74428. }
  74429. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  74430. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74431. }
  74432. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  74433. this.setTarget(targetPosition);
  74434. };
  74435. FollowCamera.prototype._checkInputs = function () {
  74436. _super.prototype._checkInputs.call(this);
  74437. if (this.lockedTarget) {
  74438. this.follow(this.lockedTarget);
  74439. }
  74440. };
  74441. FollowCamera.prototype.getClassName = function () {
  74442. return "FollowCamera";
  74443. };
  74444. __decorate([
  74445. BABYLON.serialize()
  74446. ], FollowCamera.prototype, "radius", void 0);
  74447. __decorate([
  74448. BABYLON.serialize()
  74449. ], FollowCamera.prototype, "rotationOffset", void 0);
  74450. __decorate([
  74451. BABYLON.serialize()
  74452. ], FollowCamera.prototype, "heightOffset", void 0);
  74453. __decorate([
  74454. BABYLON.serialize()
  74455. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  74456. __decorate([
  74457. BABYLON.serialize()
  74458. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  74459. __decorate([
  74460. BABYLON.serializeAsMeshReference("lockedTargetId")
  74461. ], FollowCamera.prototype, "lockedTarget", void 0);
  74462. return FollowCamera;
  74463. }(BABYLON.TargetCamera));
  74464. BABYLON.FollowCamera = FollowCamera;
  74465. var ArcFollowCamera = /** @class */ (function (_super) {
  74466. __extends(ArcFollowCamera, _super);
  74467. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  74468. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  74469. _this.alpha = alpha;
  74470. _this.beta = beta;
  74471. _this.radius = radius;
  74472. _this.target = target;
  74473. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  74474. _this.follow();
  74475. return _this;
  74476. }
  74477. ArcFollowCamera.prototype.follow = function () {
  74478. if (!this.target) {
  74479. return;
  74480. }
  74481. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  74482. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  74483. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  74484. var targetPosition = this.target.getAbsolutePosition();
  74485. this.position = targetPosition.add(this._cartesianCoordinates);
  74486. this.setTarget(targetPosition);
  74487. };
  74488. ArcFollowCamera.prototype._checkInputs = function () {
  74489. _super.prototype._checkInputs.call(this);
  74490. this.follow();
  74491. };
  74492. ArcFollowCamera.prototype.getClassName = function () {
  74493. return "ArcFollowCamera";
  74494. };
  74495. return ArcFollowCamera;
  74496. }(BABYLON.TargetCamera));
  74497. BABYLON.ArcFollowCamera = ArcFollowCamera;
  74498. })(BABYLON || (BABYLON = {}));
  74499. //# sourceMappingURL=babylon.followCamera.js.map
  74500. var BABYLON;
  74501. (function (BABYLON) {
  74502. // We're mainly based on the logic defined into the FreeCamera code
  74503. var UniversalCamera = /** @class */ (function (_super) {
  74504. __extends(UniversalCamera, _super);
  74505. //-- end properties for backward compatibility for inputs
  74506. function UniversalCamera(name, position, scene) {
  74507. var _this = _super.call(this, name, position, scene) || this;
  74508. _this.inputs.addGamepad();
  74509. return _this;
  74510. }
  74511. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  74512. //-- Begin properties for backward compatibility for inputs
  74513. get: function () {
  74514. var gamepad = this.inputs.attached["gamepad"];
  74515. if (gamepad)
  74516. return gamepad.gamepadAngularSensibility;
  74517. return 0;
  74518. },
  74519. set: function (value) {
  74520. var gamepad = this.inputs.attached["gamepad"];
  74521. if (gamepad)
  74522. gamepad.gamepadAngularSensibility = value;
  74523. },
  74524. enumerable: true,
  74525. configurable: true
  74526. });
  74527. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  74528. get: function () {
  74529. var gamepad = this.inputs.attached["gamepad"];
  74530. if (gamepad)
  74531. return gamepad.gamepadMoveSensibility;
  74532. return 0;
  74533. },
  74534. set: function (value) {
  74535. var gamepad = this.inputs.attached["gamepad"];
  74536. if (gamepad)
  74537. gamepad.gamepadMoveSensibility = value;
  74538. },
  74539. enumerable: true,
  74540. configurable: true
  74541. });
  74542. UniversalCamera.prototype.getClassName = function () {
  74543. return "UniversalCamera";
  74544. };
  74545. return UniversalCamera;
  74546. }(BABYLON.TouchCamera));
  74547. BABYLON.UniversalCamera = UniversalCamera;
  74548. })(BABYLON || (BABYLON = {}));
  74549. //# sourceMappingURL=babylon.universalCamera.js.map
  74550. var BABYLON;
  74551. (function (BABYLON) {
  74552. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  74553. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  74554. });
  74555. // We're mainly based on the logic defined into the FreeCamera code
  74556. var GamepadCamera = /** @class */ (function (_super) {
  74557. __extends(GamepadCamera, _super);
  74558. //-- end properties for backward compatibility for inputs
  74559. function GamepadCamera(name, position, scene) {
  74560. return _super.call(this, name, position, scene) || this;
  74561. }
  74562. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  74563. //-- Begin properties for backward compatibility for inputs
  74564. get: function () {
  74565. var gamepad = this.inputs.attached["gamepad"];
  74566. if (gamepad)
  74567. return gamepad.gamepadAngularSensibility;
  74568. return 0;
  74569. },
  74570. set: function (value) {
  74571. var gamepad = this.inputs.attached["gamepad"];
  74572. if (gamepad)
  74573. gamepad.gamepadAngularSensibility = value;
  74574. },
  74575. enumerable: true,
  74576. configurable: true
  74577. });
  74578. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  74579. get: function () {
  74580. var gamepad = this.inputs.attached["gamepad"];
  74581. if (gamepad)
  74582. return gamepad.gamepadMoveSensibility;
  74583. return 0;
  74584. },
  74585. set: function (value) {
  74586. var gamepad = this.inputs.attached["gamepad"];
  74587. if (gamepad)
  74588. gamepad.gamepadMoveSensibility = value;
  74589. },
  74590. enumerable: true,
  74591. configurable: true
  74592. });
  74593. GamepadCamera.prototype.getClassName = function () {
  74594. return "GamepadCamera";
  74595. };
  74596. return GamepadCamera;
  74597. }(BABYLON.UniversalCamera));
  74598. BABYLON.GamepadCamera = GamepadCamera;
  74599. })(BABYLON || (BABYLON = {}));
  74600. //# sourceMappingURL=babylon.gamepadCamera.js.map
  74601. var BABYLON;
  74602. (function (BABYLON) {
  74603. var PostProcessRenderPipelineManager = /** @class */ (function () {
  74604. function PostProcessRenderPipelineManager() {
  74605. this._renderPipelines = {};
  74606. }
  74607. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  74608. this._renderPipelines[renderPipeline._name] = renderPipeline;
  74609. };
  74610. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  74611. if (unique === void 0) { unique = false; }
  74612. var renderPipeline = this._renderPipelines[renderPipelineName];
  74613. if (!renderPipeline) {
  74614. return;
  74615. }
  74616. renderPipeline._attachCameras(cameras, unique);
  74617. };
  74618. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  74619. var renderPipeline = this._renderPipelines[renderPipelineName];
  74620. if (!renderPipeline) {
  74621. return;
  74622. }
  74623. renderPipeline._detachCameras(cameras);
  74624. };
  74625. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74626. var renderPipeline = this._renderPipelines[renderPipelineName];
  74627. if (!renderPipeline) {
  74628. return;
  74629. }
  74630. renderPipeline._enableEffect(renderEffectName, cameras);
  74631. };
  74632. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74633. var renderPipeline = this._renderPipelines[renderPipelineName];
  74634. if (!renderPipeline) {
  74635. return;
  74636. }
  74637. renderPipeline._disableEffect(renderEffectName, cameras);
  74638. };
  74639. PostProcessRenderPipelineManager.prototype.update = function () {
  74640. for (var renderPipelineName in this._renderPipelines) {
  74641. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74642. var pipeline = this._renderPipelines[renderPipelineName];
  74643. if (!pipeline.isSupported) {
  74644. pipeline.dispose();
  74645. delete this._renderPipelines[renderPipelineName];
  74646. }
  74647. else {
  74648. pipeline._update();
  74649. }
  74650. }
  74651. }
  74652. };
  74653. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  74654. for (var renderPipelineName in this._renderPipelines) {
  74655. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74656. var pipeline = this._renderPipelines[renderPipelineName];
  74657. pipeline._rebuild();
  74658. }
  74659. }
  74660. };
  74661. PostProcessRenderPipelineManager.prototype.dispose = function () {
  74662. for (var renderPipelineName in this._renderPipelines) {
  74663. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74664. var pipeline = this._renderPipelines[renderPipelineName];
  74665. pipeline.dispose();
  74666. }
  74667. }
  74668. };
  74669. return PostProcessRenderPipelineManager;
  74670. }());
  74671. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  74672. })(BABYLON || (BABYLON = {}));
  74673. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  74674. var BABYLON;
  74675. (function (BABYLON) {
  74676. /**
  74677. * This represents a set of one or more post processes in Babylon.
  74678. * A post process can be used to apply a shader to a texture after it is rendered.
  74679. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  74680. */
  74681. var PostProcessRenderEffect = /** @class */ (function () {
  74682. /**
  74683. * Instantiates a post process render effect.
  74684. * A post process can be used to apply a shader to a texture after it is rendered.
  74685. * @param engine The engine the effect is tied to
  74686. * @param name The name of the effect
  74687. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  74688. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  74689. */
  74690. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  74691. this._name = name;
  74692. this._singleInstance = singleInstance || true;
  74693. this._getPostProcesses = getPostProcesses;
  74694. this._cameras = {};
  74695. this._indicesForCamera = {};
  74696. this._postProcesses = {};
  74697. }
  74698. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  74699. /**
  74700. * Checks if all the post processes in the effect are supported.
  74701. */
  74702. get: function () {
  74703. for (var index in this._postProcesses) {
  74704. if (this._postProcesses.hasOwnProperty(index)) {
  74705. var pps = this._postProcesses[index];
  74706. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  74707. if (!pps[ppIndex].isSupported) {
  74708. return false;
  74709. }
  74710. }
  74711. }
  74712. }
  74713. return true;
  74714. },
  74715. enumerable: true,
  74716. configurable: true
  74717. });
  74718. /**
  74719. * Updates the current state of the effect
  74720. */
  74721. PostProcessRenderEffect.prototype._update = function () {
  74722. };
  74723. /**
  74724. * Attaches the effect on cameras
  74725. * @param cameras The camera to attach to.
  74726. */
  74727. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  74728. var _this = this;
  74729. var cameraKey;
  74730. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74731. if (!cams) {
  74732. return;
  74733. }
  74734. for (var i = 0; i < cams.length; i++) {
  74735. var camera = cams[i];
  74736. var cameraName = camera.name;
  74737. if (this._singleInstance) {
  74738. cameraKey = 0;
  74739. }
  74740. else {
  74741. cameraKey = cameraName;
  74742. }
  74743. if (!this._postProcesses[cameraKey]) {
  74744. var postProcess = this._getPostProcesses();
  74745. if (postProcess) {
  74746. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  74747. }
  74748. }
  74749. if (!this._indicesForCamera[cameraName]) {
  74750. this._indicesForCamera[cameraName] = [];
  74751. }
  74752. this._postProcesses[cameraKey].forEach(function (postProcess) {
  74753. var index = camera.attachPostProcess(postProcess);
  74754. _this._indicesForCamera[cameraName].push(index);
  74755. });
  74756. if (!this._cameras[cameraName]) {
  74757. this._cameras[cameraName] = camera;
  74758. }
  74759. }
  74760. };
  74761. /**
  74762. * Detatches the effect on cameras
  74763. * @param cameras The camera to detatch from.
  74764. */
  74765. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  74766. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74767. if (!cams) {
  74768. return;
  74769. }
  74770. for (var i = 0; i < cams.length; i++) {
  74771. var camera = cams[i];
  74772. var cameraName = camera.name;
  74773. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74774. camera.detachPostProcess(postProcess);
  74775. });
  74776. if (this._cameras[cameraName]) {
  74777. //this._indicesForCamera.splice(index, 1);
  74778. this._cameras[cameraName] = null;
  74779. }
  74780. }
  74781. };
  74782. /**
  74783. * Enables the effect on given cameras
  74784. * @param cameras The camera to enable.
  74785. */
  74786. PostProcessRenderEffect.prototype._enable = function (cameras) {
  74787. var _this = this;
  74788. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74789. if (!cams) {
  74790. return;
  74791. }
  74792. for (var i = 0; i < cams.length; i++) {
  74793. var camera = cams[i];
  74794. var cameraName = camera.name;
  74795. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  74796. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  74797. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74798. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  74799. });
  74800. }
  74801. }
  74802. }
  74803. };
  74804. /**
  74805. * Disables the effect on the given cameras
  74806. * @param cameras The camera to disable.
  74807. */
  74808. PostProcessRenderEffect.prototype._disable = function (cameras) {
  74809. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74810. if (!cams) {
  74811. return;
  74812. }
  74813. for (var i = 0; i < cams.length; i++) {
  74814. var camera = cams[i];
  74815. var cameraName = camera.name;
  74816. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74817. camera.detachPostProcess(postProcess);
  74818. });
  74819. }
  74820. };
  74821. /**
  74822. * Gets a list of the post processes contained in the effect.
  74823. * @param camera The camera to get the post processes on.
  74824. * @returns The list of the post processes in the effect.
  74825. */
  74826. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  74827. if (this._singleInstance) {
  74828. return this._postProcesses[0];
  74829. }
  74830. else {
  74831. if (!camera) {
  74832. return null;
  74833. }
  74834. return this._postProcesses[camera.name];
  74835. }
  74836. };
  74837. return PostProcessRenderEffect;
  74838. }());
  74839. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  74840. })(BABYLON || (BABYLON = {}));
  74841. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  74842. var BABYLON;
  74843. (function (BABYLON) {
  74844. var PostProcessRenderPipeline = /** @class */ (function () {
  74845. function PostProcessRenderPipeline(engine, name) {
  74846. this.engine = engine;
  74847. this._name = name;
  74848. this._renderEffects = {};
  74849. this._renderEffectsForIsolatedPass = new Array();
  74850. this._cameras = [];
  74851. }
  74852. PostProcessRenderPipeline.prototype.getClassName = function () {
  74853. return "PostProcessRenderPipeline";
  74854. };
  74855. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  74856. get: function () {
  74857. for (var renderEffectName in this._renderEffects) {
  74858. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74859. if (!this._renderEffects[renderEffectName].isSupported) {
  74860. return false;
  74861. }
  74862. }
  74863. }
  74864. return true;
  74865. },
  74866. enumerable: true,
  74867. configurable: true
  74868. });
  74869. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  74870. this._renderEffects[renderEffect._name] = renderEffect;
  74871. };
  74872. // private
  74873. PostProcessRenderPipeline.prototype._rebuild = function () {
  74874. };
  74875. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  74876. var renderEffects = this._renderEffects[renderEffectName];
  74877. if (!renderEffects) {
  74878. return;
  74879. }
  74880. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74881. };
  74882. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  74883. var renderEffects = this._renderEffects[renderEffectName];
  74884. if (!renderEffects) {
  74885. return;
  74886. }
  74887. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74888. };
  74889. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  74890. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74891. if (!cams) {
  74892. return;
  74893. }
  74894. var indicesToDelete = [];
  74895. var i;
  74896. for (i = 0; i < cams.length; i++) {
  74897. var camera = cams[i];
  74898. var cameraName = camera.name;
  74899. if (this._cameras.indexOf(camera) === -1) {
  74900. this._cameras[cameraName] = camera;
  74901. }
  74902. else if (unique) {
  74903. indicesToDelete.push(i);
  74904. }
  74905. }
  74906. for (i = 0; i < indicesToDelete.length; i++) {
  74907. cameras.splice(indicesToDelete[i], 1);
  74908. }
  74909. for (var renderEffectName in this._renderEffects) {
  74910. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74911. this._renderEffects[renderEffectName]._attachCameras(cams);
  74912. }
  74913. }
  74914. };
  74915. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  74916. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74917. if (!cams) {
  74918. return;
  74919. }
  74920. for (var renderEffectName in this._renderEffects) {
  74921. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74922. this._renderEffects[renderEffectName]._detachCameras(cams);
  74923. }
  74924. }
  74925. for (var i = 0; i < cams.length; i++) {
  74926. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  74927. }
  74928. };
  74929. PostProcessRenderPipeline.prototype._update = function () {
  74930. for (var renderEffectName in this._renderEffects) {
  74931. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74932. this._renderEffects[renderEffectName]._update();
  74933. }
  74934. }
  74935. for (var i = 0; i < this._cameras.length; i++) {
  74936. var cameraName = this._cameras[i].name;
  74937. if (this._renderEffectsForIsolatedPass[cameraName]) {
  74938. this._renderEffectsForIsolatedPass[cameraName]._update();
  74939. }
  74940. }
  74941. };
  74942. PostProcessRenderPipeline.prototype._reset = function () {
  74943. this._renderEffects = {};
  74944. this._renderEffectsForIsolatedPass = new Array();
  74945. };
  74946. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  74947. // 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)
  74948. var effectKeys = Object.keys(this._renderEffects);
  74949. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  74950. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  74951. if (postProcesses) {
  74952. postProcesses[0].samples = sampleCount;
  74953. return true;
  74954. }
  74955. }
  74956. return false;
  74957. };
  74958. PostProcessRenderPipeline.prototype.dispose = function () {
  74959. // Must be implemented by children
  74960. };
  74961. __decorate([
  74962. BABYLON.serialize()
  74963. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  74964. return PostProcessRenderPipeline;
  74965. }());
  74966. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  74967. })(BABYLON || (BABYLON = {}));
  74968. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  74969. var BABYLON;
  74970. (function (BABYLON) {
  74971. /**
  74972. * This represents a depth renderer in Babylon.
  74973. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  74974. */
  74975. var DepthRenderer = /** @class */ (function () {
  74976. /**
  74977. * Instantiates a depth renderer
  74978. * @param scene The scene the renderer belongs to
  74979. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  74980. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  74981. */
  74982. function DepthRenderer(scene, type, camera) {
  74983. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74984. if (camera === void 0) { camera = null; }
  74985. var _this = this;
  74986. this._scene = scene;
  74987. this._camera = camera;
  74988. var engine = scene.getEngine();
  74989. // Render target
  74990. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  74991. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74992. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74993. this._depthMap.refreshRate = 1;
  74994. this._depthMap.renderParticles = false;
  74995. this._depthMap.renderList = null;
  74996. // Camera to get depth map from to support multiple concurrent cameras
  74997. this._depthMap.activeCamera = this._camera;
  74998. this._depthMap.ignoreCameraViewport = true;
  74999. this._depthMap.useCameraPostProcesses = false;
  75000. // set default depth value to 1.0 (far away)
  75001. this._depthMap.onClearObservable.add(function (engine) {
  75002. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  75003. });
  75004. // Custom render function
  75005. var renderSubMesh = function (subMesh) {
  75006. var mesh = subMesh.getRenderingMesh();
  75007. var scene = _this._scene;
  75008. var engine = scene.getEngine();
  75009. var material = subMesh.getMaterial();
  75010. if (!material) {
  75011. return;
  75012. }
  75013. // Culling and reverse (right handed system)
  75014. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75015. // Managing instances
  75016. var batch = mesh._getInstancesRenderList(subMesh._id);
  75017. if (batch.mustReturn) {
  75018. return;
  75019. }
  75020. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75021. var camera = _this._camera || scene.activeCamera;
  75022. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  75023. engine.enableEffect(_this._effect);
  75024. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75025. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75026. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  75027. // Alpha test
  75028. if (material && material.needAlphaTesting()) {
  75029. var alphaTexture = material.getAlphaTestTexture();
  75030. if (alphaTexture) {
  75031. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75032. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75033. }
  75034. }
  75035. // Bones
  75036. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75037. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75038. }
  75039. // Draw
  75040. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75041. }
  75042. };
  75043. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75044. var index;
  75045. if (depthOnlySubMeshes.length) {
  75046. engine.setColorWrite(false);
  75047. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75048. renderSubMesh(depthOnlySubMeshes.data[index]);
  75049. }
  75050. engine.setColorWrite(true);
  75051. }
  75052. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75053. renderSubMesh(opaqueSubMeshes.data[index]);
  75054. }
  75055. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75056. renderSubMesh(alphaTestSubMeshes.data[index]);
  75057. }
  75058. };
  75059. }
  75060. /**
  75061. * Creates the depth rendering effect and checks if the effect is ready.
  75062. * @param subMesh The submesh to be used to render the depth map of
  75063. * @param useInstances If multiple world instances should be used
  75064. * @returns if the depth renderer is ready to render the depth map
  75065. */
  75066. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  75067. var material = subMesh.getMaterial();
  75068. if (material.disableDepthWrite) {
  75069. return false;
  75070. }
  75071. var defines = [];
  75072. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75073. var mesh = subMesh.getMesh();
  75074. // Alpha test
  75075. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  75076. defines.push("#define ALPHATEST");
  75077. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75078. attribs.push(BABYLON.VertexBuffer.UVKind);
  75079. defines.push("#define UV1");
  75080. }
  75081. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75082. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75083. defines.push("#define UV2");
  75084. }
  75085. }
  75086. // Bones
  75087. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75088. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75089. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75090. if (mesh.numBoneInfluencers > 4) {
  75091. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75092. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75093. }
  75094. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75095. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75096. }
  75097. else {
  75098. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75099. }
  75100. // Instances
  75101. if (useInstances) {
  75102. defines.push("#define INSTANCES");
  75103. attribs.push("world0");
  75104. attribs.push("world1");
  75105. attribs.push("world2");
  75106. attribs.push("world3");
  75107. }
  75108. // Get correct effect
  75109. var join = defines.join("\n");
  75110. if (this._cachedDefines !== join) {
  75111. this._cachedDefines = join;
  75112. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  75113. }
  75114. return this._effect.isReady();
  75115. };
  75116. /**
  75117. * Gets the texture which the depth map will be written to.
  75118. * @returns The depth map texture
  75119. */
  75120. DepthRenderer.prototype.getDepthMap = function () {
  75121. return this._depthMap;
  75122. };
  75123. /**
  75124. * Disposes of the depth renderer.
  75125. */
  75126. DepthRenderer.prototype.dispose = function () {
  75127. this._depthMap.dispose();
  75128. };
  75129. return DepthRenderer;
  75130. }());
  75131. BABYLON.DepthRenderer = DepthRenderer;
  75132. })(BABYLON || (BABYLON = {}));
  75133. //# sourceMappingURL=babylon.depthRenderer.js.map
  75134. var BABYLON;
  75135. (function (BABYLON) {
  75136. var SSAORenderingPipeline = /** @class */ (function (_super) {
  75137. __extends(SSAORenderingPipeline, _super);
  75138. /**
  75139. * @constructor
  75140. * @param {string} name - The rendering pipeline name
  75141. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75142. * @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 }
  75143. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75144. */
  75145. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  75146. var _this = _super.call(this, scene.getEngine(), name) || this;
  75147. // Members
  75148. /**
  75149. * The PassPostProcess id in the pipeline that contains the original scene color
  75150. */
  75151. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75152. /**
  75153. * The SSAO PostProcess id in the pipeline
  75154. */
  75155. _this.SSAORenderEffect = "SSAORenderEffect";
  75156. /**
  75157. * The horizontal blur PostProcess id in the pipeline
  75158. */
  75159. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75160. /**
  75161. * The vertical blur PostProcess id in the pipeline
  75162. */
  75163. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75164. /**
  75165. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75166. */
  75167. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75168. /**
  75169. * The output strength of the SSAO post-process. Default value is 1.0.
  75170. */
  75171. _this.totalStrength = 1.0;
  75172. /**
  75173. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  75174. */
  75175. _this.radius = 0.0001;
  75176. /**
  75177. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  75178. * Must not be equal to fallOff and superior to fallOff.
  75179. * Default value is 0.975
  75180. */
  75181. _this.area = 0.0075;
  75182. /**
  75183. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  75184. * Must not be equal to area and inferior to area.
  75185. * Default value is 0.0
  75186. */
  75187. _this.fallOff = 0.000001;
  75188. /**
  75189. * The base color of the SSAO post-process
  75190. * The final result is "base + ssao" between [0, 1]
  75191. */
  75192. _this.base = 0.5;
  75193. _this._firstUpdate = true;
  75194. _this._scene = scene;
  75195. // Set up assets
  75196. _this._createRandomTexture();
  75197. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75198. var ssaoRatio = ratio.ssaoRatio || ratio;
  75199. var combineRatio = ratio.combineRatio || ratio;
  75200. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75201. _this._createSSAOPostProcess(ssaoRatio);
  75202. _this._createBlurPostProcess(ssaoRatio);
  75203. _this._createSSAOCombinePostProcess(combineRatio);
  75204. // Set up pipeline
  75205. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75206. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75207. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75208. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75209. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75210. // Finish
  75211. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75212. if (cameras)
  75213. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75214. return _this;
  75215. }
  75216. // Public Methods
  75217. /**
  75218. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75219. */
  75220. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75221. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75222. for (var i = 0; i < this._scene.cameras.length; i++) {
  75223. var camera = this._scene.cameras[i];
  75224. this._originalColorPostProcess.dispose(camera);
  75225. this._ssaoPostProcess.dispose(camera);
  75226. this._blurHPostProcess.dispose(camera);
  75227. this._blurVPostProcess.dispose(camera);
  75228. this._ssaoCombinePostProcess.dispose(camera);
  75229. }
  75230. this._randomTexture.dispose();
  75231. if (disableDepthRender)
  75232. this._scene.disableDepthRenderer();
  75233. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75234. _super.prototype.dispose.call(this);
  75235. };
  75236. // Private Methods
  75237. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  75238. var _this = this;
  75239. var size = 16;
  75240. 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);
  75241. 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);
  75242. this._blurHPostProcess.onActivateObservable.add(function () {
  75243. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  75244. _this._blurHPostProcess.kernel = size * dw;
  75245. });
  75246. this._blurVPostProcess.onActivateObservable.add(function () {
  75247. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  75248. _this._blurVPostProcess.kernel = size * dw;
  75249. });
  75250. };
  75251. SSAORenderingPipeline.prototype._rebuild = function () {
  75252. this._firstUpdate = true;
  75253. _super.prototype._rebuild.call(this);
  75254. };
  75255. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75256. var _this = this;
  75257. var numSamples = 16;
  75258. var sampleSphere = [
  75259. 0.5381, 0.1856, -0.4319,
  75260. 0.1379, 0.2486, 0.4430,
  75261. 0.3371, 0.5679, -0.0057,
  75262. -0.6999, -0.0451, -0.0019,
  75263. 0.0689, -0.1598, -0.8547,
  75264. 0.0560, 0.0069, -0.1843,
  75265. -0.0146, 0.1402, 0.0762,
  75266. 0.0100, -0.1924, -0.0344,
  75267. -0.3577, -0.5301, -0.4358,
  75268. -0.3169, 0.1063, 0.0158,
  75269. 0.0103, -0.5869, 0.0046,
  75270. -0.0897, -0.4940, 0.3287,
  75271. 0.7119, -0.0154, -0.0918,
  75272. -0.0533, 0.0596, -0.5411,
  75273. 0.0352, -0.0631, 0.5460,
  75274. -0.4776, 0.2847, -0.0271
  75275. ];
  75276. var samplesFactor = 1.0 / numSamples;
  75277. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  75278. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75279. "area", "fallOff", "base", "range", "viewport"
  75280. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75281. this._ssaoPostProcess.onApply = function (effect) {
  75282. if (_this._firstUpdate) {
  75283. effect.setArray3("sampleSphere", sampleSphere);
  75284. effect.setFloat("samplesFactor", samplesFactor);
  75285. effect.setFloat("randTextureTiles", 4.0);
  75286. }
  75287. effect.setFloat("totalStrength", _this.totalStrength);
  75288. effect.setFloat("radius", _this.radius);
  75289. effect.setFloat("area", _this.area);
  75290. effect.setFloat("fallOff", _this.fallOff);
  75291. effect.setFloat("base", _this.base);
  75292. effect.setTexture("textureSampler", _this._depthTexture);
  75293. effect.setTexture("randomSampler", _this._randomTexture);
  75294. };
  75295. };
  75296. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75297. var _this = this;
  75298. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75299. this._ssaoCombinePostProcess.onApply = function (effect) {
  75300. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  75301. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75302. };
  75303. };
  75304. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  75305. var size = 512;
  75306. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75307. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75308. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75309. var context = this._randomTexture.getContext();
  75310. var rand = function (min, max) {
  75311. return Math.random() * (max - min) + min;
  75312. };
  75313. var randVector = BABYLON.Vector3.Zero();
  75314. for (var x = 0; x < size; x++) {
  75315. for (var y = 0; y < size; y++) {
  75316. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  75317. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  75318. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  75319. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75320. context.fillRect(x, y, 1, 1);
  75321. }
  75322. }
  75323. this._randomTexture.update(false);
  75324. };
  75325. __decorate([
  75326. BABYLON.serialize()
  75327. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  75328. __decorate([
  75329. BABYLON.serialize()
  75330. ], SSAORenderingPipeline.prototype, "radius", void 0);
  75331. __decorate([
  75332. BABYLON.serialize()
  75333. ], SSAORenderingPipeline.prototype, "area", void 0);
  75334. __decorate([
  75335. BABYLON.serialize()
  75336. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  75337. __decorate([
  75338. BABYLON.serialize()
  75339. ], SSAORenderingPipeline.prototype, "base", void 0);
  75340. return SSAORenderingPipeline;
  75341. }(BABYLON.PostProcessRenderPipeline));
  75342. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  75343. })(BABYLON || (BABYLON = {}));
  75344. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  75345. var BABYLON;
  75346. (function (BABYLON) {
  75347. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  75348. __extends(SSAO2RenderingPipeline, _super);
  75349. /**
  75350. * @constructor
  75351. * @param {string} name - The rendering pipeline name
  75352. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75353. * @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 }
  75354. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75355. */
  75356. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  75357. var _this = _super.call(this, scene.getEngine(), name) || this;
  75358. // Members
  75359. /**
  75360. * The PassPostProcess id in the pipeline that contains the original scene color
  75361. */
  75362. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75363. /**
  75364. * The SSAO PostProcess id in the pipeline
  75365. */
  75366. _this.SSAORenderEffect = "SSAORenderEffect";
  75367. /**
  75368. * The horizontal blur PostProcess id in the pipeline
  75369. */
  75370. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75371. /**
  75372. * The vertical blur PostProcess id in the pipeline
  75373. */
  75374. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75375. /**
  75376. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75377. */
  75378. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75379. /**
  75380. * The output strength of the SSAO post-process. Default value is 1.0.
  75381. */
  75382. _this.totalStrength = 1.0;
  75383. /**
  75384. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  75385. */
  75386. _this.maxZ = 100.0;
  75387. /**
  75388. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  75389. */
  75390. _this.minZAspect = 0.2;
  75391. /**
  75392. * Number of samples used for the SSAO calculations. Default value is 8
  75393. */
  75394. _this._samples = 8;
  75395. /**
  75396. * Are we using bilateral blur ?
  75397. */
  75398. _this._expensiveBlur = true;
  75399. /**
  75400. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  75401. */
  75402. _this.radius = 2.0;
  75403. /**
  75404. * The base color of the SSAO post-process
  75405. * The final result is "base + ssao" between [0, 1]
  75406. */
  75407. _this.base = 0.1;
  75408. _this._firstUpdate = true;
  75409. _this._scene = scene;
  75410. _this._ratio = ratio;
  75411. if (!_this.isSupported) {
  75412. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  75413. return _this;
  75414. }
  75415. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  75416. var blurRatio = _this._ratio.blurRatio || ratio;
  75417. // Set up assets
  75418. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  75419. _this._createRandomTexture();
  75420. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  75421. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  75422. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75423. _this._createSSAOPostProcess(1.0);
  75424. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  75425. _this._createSSAOCombinePostProcess(blurRatio);
  75426. // Set up pipeline
  75427. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75428. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75429. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75430. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75431. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75432. // Finish
  75433. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75434. if (cameras)
  75435. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75436. return _this;
  75437. }
  75438. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  75439. get: function () {
  75440. return this._samples;
  75441. },
  75442. set: function (n) {
  75443. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  75444. this._samples = n;
  75445. this._sampleSphere = this._generateHemisphere();
  75446. this._firstUpdate = true;
  75447. },
  75448. enumerable: true,
  75449. configurable: true
  75450. });
  75451. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  75452. get: function () {
  75453. return this._expensiveBlur;
  75454. },
  75455. set: function (b) {
  75456. 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"]);
  75457. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  75458. this._expensiveBlur = b;
  75459. this._firstUpdate = true;
  75460. },
  75461. enumerable: true,
  75462. configurable: true
  75463. });
  75464. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  75465. /**
  75466. * Support test.
  75467. */
  75468. get: function () {
  75469. var engine = BABYLON.Engine.LastCreatedEngine;
  75470. if (!engine) {
  75471. return false;
  75472. }
  75473. return engine.getCaps().drawBuffersExtension;
  75474. },
  75475. enumerable: true,
  75476. configurable: true
  75477. });
  75478. // Public Methods
  75479. /**
  75480. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75481. */
  75482. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  75483. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  75484. for (var i = 0; i < this._scene.cameras.length; i++) {
  75485. var camera = this._scene.cameras[i];
  75486. this._originalColorPostProcess.dispose(camera);
  75487. this._ssaoPostProcess.dispose(camera);
  75488. this._blurHPostProcess.dispose(camera);
  75489. this._blurVPostProcess.dispose(camera);
  75490. this._ssaoCombinePostProcess.dispose(camera);
  75491. }
  75492. this._randomTexture.dispose();
  75493. if (disableGeometryBufferRenderer)
  75494. this._scene.disableGeometryBufferRenderer();
  75495. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75496. _super.prototype.dispose.call(this);
  75497. };
  75498. // Private Methods
  75499. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  75500. var _this = this;
  75501. this._samplerOffsets = [];
  75502. var expensive = this.expensiveBlur;
  75503. for (var i = -8; i < 8; i++) {
  75504. this._samplerOffsets.push(i * 2 + 0.5);
  75505. }
  75506. 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");
  75507. this._blurHPostProcess.onApply = function (effect) {
  75508. if (!_this._scene.activeCamera) {
  75509. return;
  75510. }
  75511. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  75512. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75513. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75514. effect.setFloat("radius", _this.radius);
  75515. effect.setTexture("depthSampler", _this._depthTexture);
  75516. if (_this._firstUpdate) {
  75517. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75518. }
  75519. };
  75520. 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");
  75521. this._blurVPostProcess.onApply = function (effect) {
  75522. if (!_this._scene.activeCamera) {
  75523. return;
  75524. }
  75525. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  75526. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75527. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75528. effect.setFloat("radius", _this.radius);
  75529. effect.setTexture("depthSampler", _this._depthTexture);
  75530. if (_this._firstUpdate) {
  75531. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75532. _this._firstUpdate = false;
  75533. }
  75534. };
  75535. };
  75536. SSAO2RenderingPipeline.prototype._rebuild = function () {
  75537. this._firstUpdate = true;
  75538. _super.prototype._rebuild.call(this);
  75539. };
  75540. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  75541. var numSamples = this.samples;
  75542. var result = [];
  75543. var vector, scale;
  75544. var rand = function (min, max) {
  75545. return Math.random() * (max - min) + min;
  75546. };
  75547. var i = 0;
  75548. while (i < numSamples) {
  75549. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  75550. vector.normalize();
  75551. scale = i / numSamples;
  75552. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  75553. vector.scaleInPlace(scale);
  75554. result.push(vector.x, vector.y, vector.z);
  75555. i++;
  75556. }
  75557. return result;
  75558. };
  75559. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75560. var _this = this;
  75561. var numSamples = this.samples;
  75562. this._sampleSphere = this._generateHemisphere();
  75563. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  75564. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75565. "base", "range", "projection", "near", "far", "texelSize",
  75566. "xViewport", "yViewport", "maxZ", "minZAspect"
  75567. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75568. this._ssaoPostProcess.onApply = function (effect) {
  75569. if (_this._firstUpdate) {
  75570. effect.setArray3("sampleSphere", _this._sampleSphere);
  75571. effect.setFloat("randTextureTiles", 4.0);
  75572. }
  75573. if (!_this._scene.activeCamera) {
  75574. return;
  75575. }
  75576. effect.setFloat("samplesFactor", 1 / _this.samples);
  75577. effect.setFloat("totalStrength", _this.totalStrength);
  75578. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  75579. effect.setFloat("radius", _this.radius);
  75580. effect.setFloat("maxZ", _this.maxZ);
  75581. effect.setFloat("minZAspect", _this.minZAspect);
  75582. effect.setFloat("base", _this.base);
  75583. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75584. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75585. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  75586. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  75587. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  75588. effect.setTexture("textureSampler", _this._depthTexture);
  75589. effect.setTexture("normalSampler", _this._normalTexture);
  75590. effect.setTexture("randomSampler", _this._randomTexture);
  75591. };
  75592. };
  75593. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75594. var _this = this;
  75595. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75596. this._ssaoCombinePostProcess.onApply = function (effect) {
  75597. var viewport = _this._scene.activeCamera.viewport;
  75598. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  75599. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75600. };
  75601. };
  75602. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  75603. var size = 512;
  75604. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75605. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75606. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75607. var context = this._randomTexture.getContext();
  75608. var rand = function (min, max) {
  75609. return Math.random() * (max - min) + min;
  75610. };
  75611. var randVector = BABYLON.Vector3.Zero();
  75612. for (var x = 0; x < size; x++) {
  75613. for (var y = 0; y < size; y++) {
  75614. randVector.x = rand(0.0, 1.0);
  75615. randVector.y = rand(0.0, 1.0);
  75616. randVector.z = 0.0;
  75617. randVector.normalize();
  75618. randVector.scaleInPlace(255);
  75619. randVector.x = Math.floor(randVector.x);
  75620. randVector.y = Math.floor(randVector.y);
  75621. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75622. context.fillRect(x, y, 1, 1);
  75623. }
  75624. }
  75625. this._randomTexture.update(false);
  75626. };
  75627. /**
  75628. * Serialize the rendering pipeline (Used when exporting)
  75629. * @returns the serialized object
  75630. */
  75631. SSAO2RenderingPipeline.prototype.serialize = function () {
  75632. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75633. serializationObject.customType = "SSAO2RenderingPipeline";
  75634. return serializationObject;
  75635. };
  75636. /**
  75637. * Parse the serialized pipeline
  75638. * @param source Source pipeline.
  75639. * @param scene The scene to load the pipeline to.
  75640. * @param rootUrl The URL of the serialized pipeline.
  75641. * @returns An instantiated pipeline from the serialized object.
  75642. */
  75643. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  75644. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75645. };
  75646. __decorate([
  75647. BABYLON.serialize()
  75648. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  75649. __decorate([
  75650. BABYLON.serialize()
  75651. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  75652. __decorate([
  75653. BABYLON.serialize()
  75654. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  75655. __decorate([
  75656. BABYLON.serialize("samples")
  75657. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  75658. __decorate([
  75659. BABYLON.serialize()
  75660. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  75661. __decorate([
  75662. BABYLON.serialize("expensiveBlur")
  75663. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  75664. __decorate([
  75665. BABYLON.serialize()
  75666. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  75667. __decorate([
  75668. BABYLON.serialize()
  75669. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  75670. return SSAO2RenderingPipeline;
  75671. }(BABYLON.PostProcessRenderPipeline));
  75672. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  75673. })(BABYLON || (BABYLON = {}));
  75674. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  75675. // BABYLON.JS Chromatic Aberration GLSL Shader
  75676. // Author: Olivier Guyot
  75677. // Separates very slightly R, G and B colors on the edges of the screen
  75678. // Inspired by Francois Tarlier & Martins Upitis
  75679. var BABYLON;
  75680. (function (BABYLON) {
  75681. var LensRenderingPipeline = /** @class */ (function (_super) {
  75682. __extends(LensRenderingPipeline, _super);
  75683. /**
  75684. * @constructor
  75685. *
  75686. * Effect parameters are as follow:
  75687. * {
  75688. * chromatic_aberration: number; // from 0 to x (1 for realism)
  75689. * edge_blur: number; // from 0 to x (1 for realism)
  75690. * distortion: number; // from 0 to x (1 for realism)
  75691. * grain_amount: number; // from 0 to 1
  75692. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  75693. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  75694. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  75695. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  75696. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  75697. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  75698. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  75699. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  75700. * }
  75701. * Note: if an effect parameter is unset, effect is disabled
  75702. *
  75703. * @param {string} name - The rendering pipeline name
  75704. * @param {object} parameters - An object containing all parameters (see above)
  75705. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75706. * @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)
  75707. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75708. */
  75709. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  75710. if (ratio === void 0) { ratio = 1.0; }
  75711. var _this = _super.call(this, scene.getEngine(), name) || this;
  75712. // Lens effects can be of the following:
  75713. // - chromatic aberration (slight shift of RGB colors)
  75714. // - blur on the edge of the lens
  75715. // - lens distortion
  75716. // - depth-of-field blur & highlights enhancing
  75717. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  75718. // - grain effect (noise or custom texture)
  75719. // Two additional texture samplers are needed:
  75720. // - depth map (for depth-of-field)
  75721. // - grain texture
  75722. /**
  75723. * The chromatic aberration PostProcess id in the pipeline
  75724. */
  75725. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  75726. /**
  75727. * The highlights enhancing PostProcess id in the pipeline
  75728. */
  75729. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  75730. /**
  75731. * The depth-of-field PostProcess id in the pipeline
  75732. */
  75733. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  75734. _this._scene = scene;
  75735. // Fetch texture samplers
  75736. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75737. if (parameters.grain_texture) {
  75738. _this._grainTexture = parameters.grain_texture;
  75739. }
  75740. else {
  75741. _this._createGrainTexture();
  75742. }
  75743. // save parameters
  75744. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  75745. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  75746. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  75747. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  75748. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  75749. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  75750. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  75751. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  75752. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  75753. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  75754. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  75755. // Create effects
  75756. _this._createChromaticAberrationPostProcess(ratio);
  75757. _this._createHighlightsPostProcess(ratio);
  75758. _this._createDepthOfFieldPostProcess(ratio / 4);
  75759. // Set up pipeline
  75760. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  75761. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  75762. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  75763. if (_this._highlightsGain === -1) {
  75764. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  75765. }
  75766. // Finish
  75767. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75768. if (cameras) {
  75769. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75770. }
  75771. return _this;
  75772. }
  75773. // public methods (self explanatory)
  75774. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  75775. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  75776. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  75777. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  75778. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  75779. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  75780. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  75781. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  75782. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  75783. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  75784. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  75785. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  75786. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  75787. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  75788. };
  75789. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  75790. this._highlightsPostProcess.updateEffect();
  75791. };
  75792. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  75793. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  75794. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  75795. this._highlightsGain = amount;
  75796. };
  75797. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  75798. if (this._highlightsGain === -1) {
  75799. this._highlightsGain = 1.0;
  75800. }
  75801. this._highlightsThreshold = amount;
  75802. };
  75803. LensRenderingPipeline.prototype.disableHighlights = function () {
  75804. this._highlightsGain = -1;
  75805. };
  75806. /**
  75807. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  75808. */
  75809. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75810. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75811. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75812. this._chromaticAberrationPostProcess = null;
  75813. this._highlightsPostProcess = null;
  75814. this._depthOfFieldPostProcess = null;
  75815. this._grainTexture.dispose();
  75816. if (disableDepthRender)
  75817. this._scene.disableDepthRenderer();
  75818. };
  75819. // colors shifting and distortion
  75820. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  75821. var _this = this;
  75822. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  75823. [], // samplers
  75824. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75825. this._chromaticAberrationPostProcess.onApply = function (effect) {
  75826. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  75827. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75828. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75829. effect.setFloat('radialIntensity', 1);
  75830. effect.setFloat2('direction', 17, 17);
  75831. effect.setFloat2('centerPosition', 0.5, 0.5);
  75832. };
  75833. };
  75834. // highlights enhancing
  75835. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  75836. var _this = this;
  75837. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  75838. [], // samplers
  75839. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  75840. this._highlightsPostProcess.onApply = function (effect) {
  75841. effect.setFloat('gain', _this._highlightsGain);
  75842. effect.setFloat('threshold', _this._highlightsThreshold);
  75843. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  75844. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75845. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75846. };
  75847. };
  75848. // colors shifting and distortion
  75849. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  75850. var _this = this;
  75851. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  75852. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  75853. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  75854. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75855. this._depthOfFieldPostProcess.onApply = function (effect) {
  75856. effect.setTexture("depthSampler", _this._depthTexture);
  75857. effect.setTexture("grainSampler", _this._grainTexture);
  75858. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  75859. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  75860. effect.setFloat('grain_amount', _this._grainAmount);
  75861. effect.setBool('blur_noise', _this._blurNoise);
  75862. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75863. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75864. effect.setFloat('distortion', _this._distortion);
  75865. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  75866. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  75867. effect.setFloat('aperture', _this._dofAperture);
  75868. effect.setFloat('darken', _this._dofDarken);
  75869. effect.setFloat('edge_blur', _this._edgeBlur);
  75870. effect.setBool('highlights', (_this._highlightsGain !== -1));
  75871. if (_this._scene.activeCamera) {
  75872. effect.setFloat('near', _this._scene.activeCamera.minZ);
  75873. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  75874. }
  75875. };
  75876. };
  75877. // creates a black and white random noise texture, 512x512
  75878. LensRenderingPipeline.prototype._createGrainTexture = function () {
  75879. var size = 512;
  75880. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75881. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75882. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75883. var context = this._grainTexture.getContext();
  75884. var rand = function (min, max) {
  75885. return Math.random() * (max - min) + min;
  75886. };
  75887. var value;
  75888. for (var x = 0; x < size; x++) {
  75889. for (var y = 0; y < size; y++) {
  75890. value = Math.floor(rand(0.42, 0.58) * 255);
  75891. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  75892. context.fillRect(x, y, 1, 1);
  75893. }
  75894. }
  75895. this._grainTexture.update(false);
  75896. };
  75897. return LensRenderingPipeline;
  75898. }(BABYLON.PostProcessRenderPipeline));
  75899. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  75900. })(BABYLON || (BABYLON = {}));
  75901. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  75902. var BABYLON;
  75903. (function (BABYLON) {
  75904. var StandardRenderingPipeline = /** @class */ (function (_super) {
  75905. __extends(StandardRenderingPipeline, _super);
  75906. /**
  75907. * @constructor
  75908. * @param {string} name - The rendering pipeline name
  75909. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75910. * @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)
  75911. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  75912. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75913. */
  75914. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  75915. if (originalPostProcess === void 0) { originalPostProcess = null; }
  75916. var _this = _super.call(this, scene.getEngine(), name) || this;
  75917. _this.downSampleX4PostProcess = null;
  75918. _this.brightPassPostProcess = null;
  75919. _this.blurHPostProcesses = [];
  75920. _this.blurVPostProcesses = [];
  75921. _this.textureAdderPostProcess = null;
  75922. _this.volumetricLightPostProcess = null;
  75923. _this.volumetricLightSmoothXPostProcess = null;
  75924. _this.volumetricLightSmoothYPostProcess = null;
  75925. _this.volumetricLightMergePostProces = null;
  75926. _this.volumetricLightFinalPostProcess = null;
  75927. _this.luminancePostProcess = null;
  75928. _this.luminanceDownSamplePostProcesses = [];
  75929. _this.hdrPostProcess = null;
  75930. _this.textureAdderFinalPostProcess = null;
  75931. _this.lensFlareFinalPostProcess = null;
  75932. _this.hdrFinalPostProcess = null;
  75933. _this.lensFlarePostProcess = null;
  75934. _this.lensFlareComposePostProcess = null;
  75935. _this.motionBlurPostProcess = null;
  75936. _this.depthOfFieldPostProcess = null;
  75937. // Values
  75938. _this.brightThreshold = 1.0;
  75939. _this.blurWidth = 512.0;
  75940. _this.horizontalBlur = false;
  75941. _this.exposure = 1.0;
  75942. _this.lensTexture = null;
  75943. _this.volumetricLightCoefficient = 0.2;
  75944. _this.volumetricLightPower = 4.0;
  75945. _this.volumetricLightBlurScale = 64.0;
  75946. _this.sourceLight = null;
  75947. _this.hdrMinimumLuminance = 1.0;
  75948. _this.hdrDecreaseRate = 0.5;
  75949. _this.hdrIncreaseRate = 0.5;
  75950. _this.lensColorTexture = null;
  75951. _this.lensFlareStrength = 20.0;
  75952. _this.lensFlareGhostDispersal = 1.4;
  75953. _this.lensFlareHaloWidth = 0.7;
  75954. _this.lensFlareDistortionStrength = 16.0;
  75955. _this.lensStarTexture = null;
  75956. _this.lensFlareDirtTexture = null;
  75957. _this.depthOfFieldDistance = 10.0;
  75958. _this.depthOfFieldBlurWidth = 64.0;
  75959. _this.motionStrength = 1.0;
  75960. // IAnimatable
  75961. _this.animations = [];
  75962. _this._currentDepthOfFieldSource = null;
  75963. _this._hdrCurrentLuminance = 1.0;
  75964. // Getters and setters
  75965. _this._bloomEnabled = true;
  75966. _this._depthOfFieldEnabled = false;
  75967. _this._vlsEnabled = false;
  75968. _this._lensFlareEnabled = false;
  75969. _this._hdrEnabled = false;
  75970. _this._motionBlurEnabled = false;
  75971. _this._motionBlurSamples = 64.0;
  75972. _this._volumetricLightStepsCount = 50.0;
  75973. _this._cameras = cameras || [];
  75974. // Initialize
  75975. _this._scene = scene;
  75976. _this._basePostProcess = originalPostProcess;
  75977. _this._ratio = ratio;
  75978. // Misc
  75979. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75980. // Finish
  75981. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75982. _this._buildPipeline();
  75983. return _this;
  75984. }
  75985. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  75986. get: function () {
  75987. return this._bloomEnabled;
  75988. },
  75989. set: function (enabled) {
  75990. if (this._bloomEnabled === enabled) {
  75991. return;
  75992. }
  75993. this._bloomEnabled = enabled;
  75994. this._buildPipeline();
  75995. },
  75996. enumerable: true,
  75997. configurable: true
  75998. });
  75999. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  76000. get: function () {
  76001. return this._depthOfFieldEnabled;
  76002. },
  76003. set: function (enabled) {
  76004. if (this._depthOfFieldEnabled === enabled) {
  76005. return;
  76006. }
  76007. this._depthOfFieldEnabled = enabled;
  76008. this._buildPipeline();
  76009. },
  76010. enumerable: true,
  76011. configurable: true
  76012. });
  76013. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  76014. get: function () {
  76015. return this._lensFlareEnabled;
  76016. },
  76017. set: function (enabled) {
  76018. if (this._lensFlareEnabled === enabled) {
  76019. return;
  76020. }
  76021. this._lensFlareEnabled = enabled;
  76022. this._buildPipeline();
  76023. },
  76024. enumerable: true,
  76025. configurable: true
  76026. });
  76027. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  76028. get: function () {
  76029. return this._hdrEnabled;
  76030. },
  76031. set: function (enabled) {
  76032. if (this._hdrEnabled === enabled) {
  76033. return;
  76034. }
  76035. this._hdrEnabled = enabled;
  76036. this._buildPipeline();
  76037. },
  76038. enumerable: true,
  76039. configurable: true
  76040. });
  76041. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  76042. get: function () {
  76043. return this._vlsEnabled;
  76044. },
  76045. set: function (enabled) {
  76046. if (this._vlsEnabled === enabled) {
  76047. return;
  76048. }
  76049. if (enabled) {
  76050. var geometry = this._scene.enableGeometryBufferRenderer();
  76051. if (!geometry) {
  76052. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  76053. return;
  76054. }
  76055. }
  76056. this._vlsEnabled = enabled;
  76057. this._buildPipeline();
  76058. },
  76059. enumerable: true,
  76060. configurable: true
  76061. });
  76062. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  76063. get: function () {
  76064. return this._motionBlurEnabled;
  76065. },
  76066. set: function (enabled) {
  76067. if (this._motionBlurEnabled === enabled) {
  76068. return;
  76069. }
  76070. this._motionBlurEnabled = enabled;
  76071. this._buildPipeline();
  76072. },
  76073. enumerable: true,
  76074. configurable: true
  76075. });
  76076. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  76077. get: function () {
  76078. return this._volumetricLightStepsCount;
  76079. },
  76080. set: function (count) {
  76081. if (this.volumetricLightPostProcess) {
  76082. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  76083. }
  76084. this._volumetricLightStepsCount = count;
  76085. },
  76086. enumerable: true,
  76087. configurable: true
  76088. });
  76089. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  76090. get: function () {
  76091. return this._motionBlurSamples;
  76092. },
  76093. set: function (samples) {
  76094. if (this.motionBlurPostProcess) {
  76095. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  76096. }
  76097. this._motionBlurSamples = samples;
  76098. },
  76099. enumerable: true,
  76100. configurable: true
  76101. });
  76102. StandardRenderingPipeline.prototype._buildPipeline = function () {
  76103. var _this = this;
  76104. var ratio = this._ratio;
  76105. var scene = this._scene;
  76106. this._disposePostProcesses();
  76107. this._reset();
  76108. // Create pass post-process
  76109. if (!this._basePostProcess) {
  76110. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  76111. this.originalPostProcess.onApply = function (effect) {
  76112. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  76113. };
  76114. }
  76115. else {
  76116. this.originalPostProcess = this._basePostProcess;
  76117. }
  76118. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  76119. this._currentDepthOfFieldSource = this.originalPostProcess;
  76120. if (this._bloomEnabled) {
  76121. // Create down sample X4 post-process
  76122. this._createDownSampleX4PostProcess(scene, ratio / 2);
  76123. // Create bright pass post-process
  76124. this._createBrightPassPostProcess(scene, ratio / 2);
  76125. // Create gaussian blur post-processes (down sampling blurs)
  76126. this._createBlurPostProcesses(scene, ratio / 4, 1);
  76127. // Create texture adder post-process
  76128. this._createTextureAdderPostProcess(scene, ratio);
  76129. // Create depth-of-field source post-process
  76130. 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);
  76131. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  76132. }
  76133. if (this._vlsEnabled) {
  76134. // Create volumetric light
  76135. this._createVolumetricLightPostProcess(scene, ratio);
  76136. // Create volumetric light final post-process
  76137. 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);
  76138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  76139. }
  76140. if (this._lensFlareEnabled) {
  76141. // Create lens flare post-process
  76142. this._createLensFlarePostProcess(scene, ratio);
  76143. // Create depth-of-field source post-process post lens-flare and disable it now
  76144. 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);
  76145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  76146. }
  76147. if (this._hdrEnabled) {
  76148. // Create luminance
  76149. this._createLuminancePostProcesses(scene, this._floatTextureType);
  76150. // Create HDR
  76151. this._createHdrPostProcess(scene, ratio);
  76152. // Create depth-of-field source post-process post hdr and disable it now
  76153. 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);
  76154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  76155. }
  76156. if (this._depthOfFieldEnabled) {
  76157. // Create gaussian blur used by depth-of-field
  76158. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  76159. // Create depth-of-field post-process
  76160. this._createDepthOfFieldPostProcess(scene, ratio);
  76161. }
  76162. if (this._motionBlurEnabled) {
  76163. // Create motion blur post-process
  76164. this._createMotionBlurPostProcess(scene, ratio);
  76165. }
  76166. if (this._cameras !== null) {
  76167. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76168. }
  76169. };
  76170. // Down Sample X4 Post-Processs
  76171. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  76172. var _this = this;
  76173. var downSampleX4Offsets = new Array(32);
  76174. 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);
  76175. this.downSampleX4PostProcess.onApply = function (effect) {
  76176. var id = 0;
  76177. var width = _this.downSampleX4PostProcess.width;
  76178. var height = _this.downSampleX4PostProcess.height;
  76179. for (var i = -2; i < 2; i++) {
  76180. for (var j = -2; j < 2; j++) {
  76181. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  76182. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  76183. id += 2;
  76184. }
  76185. }
  76186. effect.setArray2("dsOffsets", downSampleX4Offsets);
  76187. };
  76188. // Add to pipeline
  76189. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  76190. };
  76191. // Brightpass Post-Process
  76192. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  76193. var _this = this;
  76194. var brightOffsets = new Array(8);
  76195. 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);
  76196. this.brightPassPostProcess.onApply = function (effect) {
  76197. var sU = (1.0 / _this.brightPassPostProcess.width);
  76198. var sV = (1.0 / _this.brightPassPostProcess.height);
  76199. brightOffsets[0] = -0.5 * sU;
  76200. brightOffsets[1] = 0.5 * sV;
  76201. brightOffsets[2] = 0.5 * sU;
  76202. brightOffsets[3] = 0.5 * sV;
  76203. brightOffsets[4] = -0.5 * sU;
  76204. brightOffsets[5] = -0.5 * sV;
  76205. brightOffsets[6] = 0.5 * sU;
  76206. brightOffsets[7] = -0.5 * sV;
  76207. effect.setArray2("dsOffsets", brightOffsets);
  76208. effect.setFloat("brightThreshold", _this.brightThreshold);
  76209. };
  76210. // Add to pipeline
  76211. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  76212. };
  76213. // Create blur H&V post-processes
  76214. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  76215. var _this = this;
  76216. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  76217. var engine = scene.getEngine();
  76218. 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);
  76219. 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);
  76220. blurX.onActivateObservable.add(function () {
  76221. var dw = blurX.width / engine.getRenderWidth();
  76222. blurX.kernel = _this[blurWidthKey] * dw;
  76223. });
  76224. blurY.onActivateObservable.add(function () {
  76225. var dw = blurY.height / engine.getRenderHeight();
  76226. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  76227. });
  76228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  76229. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  76230. this.blurHPostProcesses.push(blurX);
  76231. this.blurVPostProcesses.push(blurY);
  76232. };
  76233. // Create texture adder post-process
  76234. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  76235. var _this = this;
  76236. 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);
  76237. this.textureAdderPostProcess.onApply = function (effect) {
  76238. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  76239. effect.setTexture("lensSampler", _this.lensTexture);
  76240. effect.setFloat("exposure", _this.exposure);
  76241. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  76242. };
  76243. // Add to pipeline
  76244. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  76245. };
  76246. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  76247. var _this = this;
  76248. var geometryRenderer = scene.enableGeometryBufferRenderer();
  76249. geometryRenderer.enablePosition = true;
  76250. var geometry = geometryRenderer.getGBuffer();
  76251. // Base post-process
  76252. 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));
  76253. var depthValues = BABYLON.Vector2.Zero();
  76254. this.volumetricLightPostProcess.onApply = function (effect) {
  76255. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  76256. var generator = _this.sourceLight.getShadowGenerator();
  76257. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  76258. effect.setTexture("positionSampler", geometry.textures[2]);
  76259. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  76260. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  76261. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  76262. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  76263. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  76264. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  76265. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  76266. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  76267. effect.setVector2("depthValues", depthValues);
  76268. }
  76269. };
  76270. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  76271. // Smooth
  76272. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  76273. // Merge
  76274. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  76275. this.volumetricLightMergePostProces.onApply = function (effect) {
  76276. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  76277. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  76278. };
  76279. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  76280. };
  76281. // Create luminance
  76282. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  76283. var _this = this;
  76284. // Create luminance
  76285. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  76286. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  76287. var offsets = [];
  76288. this.luminancePostProcess.onApply = function (effect) {
  76289. var sU = (1.0 / _this.luminancePostProcess.width);
  76290. var sV = (1.0 / _this.luminancePostProcess.height);
  76291. offsets[0] = -0.5 * sU;
  76292. offsets[1] = 0.5 * sV;
  76293. offsets[2] = 0.5 * sU;
  76294. offsets[3] = 0.5 * sV;
  76295. offsets[4] = -0.5 * sU;
  76296. offsets[5] = -0.5 * sV;
  76297. offsets[6] = 0.5 * sU;
  76298. offsets[7] = -0.5 * sV;
  76299. effect.setArray2("lumOffsets", offsets);
  76300. };
  76301. // Add to pipeline
  76302. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  76303. // Create down sample luminance
  76304. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  76305. var size = Math.pow(3, i);
  76306. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  76307. if (i === 0) {
  76308. defines += "#define FINAL_DOWN_SAMPLER";
  76309. }
  76310. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  76311. this.luminanceDownSamplePostProcesses.push(postProcess);
  76312. }
  76313. // Create callbacks and add effects
  76314. var lastLuminance = this.luminancePostProcess;
  76315. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  76316. var downSampleOffsets = new Array(18);
  76317. pp.onApply = function (effect) {
  76318. if (!lastLuminance) {
  76319. return;
  76320. }
  76321. var id = 0;
  76322. for (var x = -1; x < 2; x++) {
  76323. for (var y = -1; y < 2; y++) {
  76324. downSampleOffsets[id] = x / lastLuminance.width;
  76325. downSampleOffsets[id + 1] = y / lastLuminance.height;
  76326. id += 2;
  76327. }
  76328. }
  76329. effect.setArray2("dsOffsets", downSampleOffsets);
  76330. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  76331. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76332. lastLuminance = _this.luminancePostProcess;
  76333. }
  76334. else {
  76335. lastLuminance = pp;
  76336. }
  76337. };
  76338. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76339. pp.onAfterRender = function (effect) {
  76340. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  76341. 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);
  76342. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  76343. };
  76344. }
  76345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  76346. });
  76347. };
  76348. // Create HDR post-process
  76349. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  76350. var _this = this;
  76351. 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);
  76352. var outputLiminance = 1;
  76353. var time = 0;
  76354. var lastTime = 0;
  76355. this.hdrPostProcess.onApply = function (effect) {
  76356. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  76357. time += scene.getEngine().getDeltaTime();
  76358. if (outputLiminance < 0) {
  76359. outputLiminance = _this._hdrCurrentLuminance;
  76360. }
  76361. else {
  76362. var dt = (lastTime - time) / 1000.0;
  76363. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  76364. outputLiminance += _this.hdrDecreaseRate * dt;
  76365. }
  76366. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  76367. outputLiminance -= _this.hdrIncreaseRate * dt;
  76368. }
  76369. else {
  76370. outputLiminance = _this._hdrCurrentLuminance;
  76371. }
  76372. }
  76373. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  76374. effect.setFloat("averageLuminance", outputLiminance);
  76375. lastTime = time;
  76376. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  76377. };
  76378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  76379. };
  76380. // Create lens flare post-process
  76381. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  76382. var _this = this;
  76383. 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);
  76384. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  76385. this._createBlurPostProcesses(scene, ratio / 4, 2);
  76386. 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);
  76387. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  76388. var resolution = new BABYLON.Vector2(0, 0);
  76389. // Lens flare
  76390. this.lensFlarePostProcess.onApply = function (effect) {
  76391. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  76392. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  76393. effect.setFloat("strength", _this.lensFlareStrength);
  76394. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  76395. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  76396. // Shift
  76397. resolution.x = _this.lensFlarePostProcess.width;
  76398. resolution.y = _this.lensFlarePostProcess.height;
  76399. effect.setVector2("resolution", resolution);
  76400. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  76401. };
  76402. // Compose
  76403. 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);
  76404. 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);
  76405. this.lensFlareComposePostProcess.onApply = function (effect) {
  76406. if (!_this._scene.activeCamera) {
  76407. return;
  76408. }
  76409. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76410. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  76411. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  76412. // Lens start rotation matrix
  76413. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  76414. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  76415. 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));
  76416. camRot *= 4.0;
  76417. 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);
  76418. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  76419. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  76420. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  76421. };
  76422. };
  76423. // Create depth-of-field post-process
  76424. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  76425. var _this = this;
  76426. 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);
  76427. this.depthOfFieldPostProcess.onApply = function (effect) {
  76428. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76429. effect.setTexture("depthSampler", _this._getDepthTexture());
  76430. effect.setFloat("distance", _this.depthOfFieldDistance);
  76431. };
  76432. // Add to pipeline
  76433. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  76434. };
  76435. // Create motion blur post-process
  76436. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  76437. var _this = this;
  76438. 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);
  76439. var motionScale = 0;
  76440. var prevViewProjection = BABYLON.Matrix.Identity();
  76441. var invViewProjection = BABYLON.Matrix.Identity();
  76442. var viewProjection = BABYLON.Matrix.Identity();
  76443. var screenSize = BABYLON.Vector2.Zero();
  76444. this.motionBlurPostProcess.onApply = function (effect) {
  76445. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  76446. viewProjection.invertToRef(invViewProjection);
  76447. effect.setMatrix("inverseViewProjection", invViewProjection);
  76448. effect.setMatrix("prevViewProjection", prevViewProjection);
  76449. prevViewProjection = viewProjection;
  76450. screenSize.x = _this.motionBlurPostProcess.width;
  76451. screenSize.y = _this.motionBlurPostProcess.height;
  76452. effect.setVector2("screenSize", screenSize);
  76453. motionScale = scene.getEngine().getFps() / 60.0;
  76454. effect.setFloat("motionScale", motionScale);
  76455. effect.setFloat("motionStrength", _this.motionStrength);
  76456. effect.setTexture("depthSampler", _this._getDepthTexture());
  76457. };
  76458. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  76459. };
  76460. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  76461. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  76462. var renderer = this._scene.enableGeometryBufferRenderer();
  76463. return renderer.getGBuffer().textures[0];
  76464. }
  76465. return this._scene.enableDepthRenderer().getDepthMap();
  76466. };
  76467. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  76468. for (var i = 0; i < this._cameras.length; i++) {
  76469. var camera = this._cameras[i];
  76470. if (this.originalPostProcess) {
  76471. this.originalPostProcess.dispose(camera);
  76472. }
  76473. if (this.downSampleX4PostProcess) {
  76474. this.downSampleX4PostProcess.dispose(camera);
  76475. }
  76476. if (this.brightPassPostProcess) {
  76477. this.brightPassPostProcess.dispose(camera);
  76478. }
  76479. if (this.textureAdderPostProcess) {
  76480. this.textureAdderPostProcess.dispose(camera);
  76481. }
  76482. if (this.textureAdderFinalPostProcess) {
  76483. this.textureAdderFinalPostProcess.dispose(camera);
  76484. }
  76485. if (this.volumetricLightPostProcess) {
  76486. this.volumetricLightPostProcess.dispose(camera);
  76487. }
  76488. if (this.volumetricLightSmoothXPostProcess) {
  76489. this.volumetricLightSmoothXPostProcess.dispose(camera);
  76490. }
  76491. if (this.volumetricLightSmoothYPostProcess) {
  76492. this.volumetricLightSmoothYPostProcess.dispose(camera);
  76493. }
  76494. if (this.volumetricLightMergePostProces) {
  76495. this.volumetricLightMergePostProces.dispose(camera);
  76496. }
  76497. if (this.volumetricLightFinalPostProcess) {
  76498. this.volumetricLightFinalPostProcess.dispose(camera);
  76499. }
  76500. if (this.lensFlarePostProcess) {
  76501. this.lensFlarePostProcess.dispose(camera);
  76502. }
  76503. if (this.lensFlareComposePostProcess) {
  76504. this.lensFlareComposePostProcess.dispose(camera);
  76505. }
  76506. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  76507. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  76508. }
  76509. if (this.luminancePostProcess) {
  76510. this.luminancePostProcess.dispose(camera);
  76511. }
  76512. if (this.hdrPostProcess) {
  76513. this.hdrPostProcess.dispose(camera);
  76514. }
  76515. if (this.hdrFinalPostProcess) {
  76516. this.hdrFinalPostProcess.dispose(camera);
  76517. }
  76518. if (this.depthOfFieldPostProcess) {
  76519. this.depthOfFieldPostProcess.dispose(camera);
  76520. }
  76521. if (this.motionBlurPostProcess) {
  76522. this.motionBlurPostProcess.dispose(camera);
  76523. }
  76524. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  76525. this.blurHPostProcesses[j].dispose(camera);
  76526. }
  76527. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  76528. this.blurVPostProcesses[j].dispose(camera);
  76529. }
  76530. }
  76531. this.originalPostProcess = null;
  76532. this.downSampleX4PostProcess = null;
  76533. this.brightPassPostProcess = null;
  76534. this.textureAdderPostProcess = null;
  76535. this.textureAdderFinalPostProcess = null;
  76536. this.volumetricLightPostProcess = null;
  76537. this.volumetricLightSmoothXPostProcess = null;
  76538. this.volumetricLightSmoothYPostProcess = null;
  76539. this.volumetricLightMergePostProces = null;
  76540. this.volumetricLightFinalPostProcess = null;
  76541. this.lensFlarePostProcess = null;
  76542. this.lensFlareComposePostProcess = null;
  76543. this.luminancePostProcess = null;
  76544. this.hdrPostProcess = null;
  76545. this.hdrFinalPostProcess = null;
  76546. this.depthOfFieldPostProcess = null;
  76547. this.motionBlurPostProcess = null;
  76548. this.luminanceDownSamplePostProcesses = [];
  76549. this.blurHPostProcesses = [];
  76550. this.blurVPostProcesses = [];
  76551. };
  76552. /**
  76553. * Dispose of the pipeline and stop all post processes
  76554. */
  76555. StandardRenderingPipeline.prototype.dispose = function () {
  76556. this._disposePostProcesses();
  76557. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76558. _super.prototype.dispose.call(this);
  76559. };
  76560. /**
  76561. * Serialize the rendering pipeline (Used when exporting)
  76562. * @returns the serialized object
  76563. */
  76564. StandardRenderingPipeline.prototype.serialize = function () {
  76565. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76566. if (this.sourceLight) {
  76567. serializationObject.sourceLightId = this.sourceLight.id;
  76568. }
  76569. serializationObject.customType = "StandardRenderingPipeline";
  76570. return serializationObject;
  76571. };
  76572. /**
  76573. * Parse the serialized pipeline
  76574. * @param source Source pipeline.
  76575. * @param scene The scene to load the pipeline to.
  76576. * @param rootUrl The URL of the serialized pipeline.
  76577. * @returns An instantiated pipeline from the serialized object.
  76578. */
  76579. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76580. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76581. if (source.sourceLightId) {
  76582. p.sourceLight = scene.getLightByID(source.sourceLightId);
  76583. }
  76584. return p;
  76585. };
  76586. // Luminance steps
  76587. StandardRenderingPipeline.LuminanceSteps = 6;
  76588. __decorate([
  76589. BABYLON.serialize()
  76590. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  76591. __decorate([
  76592. BABYLON.serialize()
  76593. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  76594. __decorate([
  76595. BABYLON.serialize()
  76596. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  76597. __decorate([
  76598. BABYLON.serialize()
  76599. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  76600. __decorate([
  76601. BABYLON.serializeAsTexture("lensTexture")
  76602. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  76603. __decorate([
  76604. BABYLON.serialize()
  76605. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  76606. __decorate([
  76607. BABYLON.serialize()
  76608. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  76609. __decorate([
  76610. BABYLON.serialize()
  76611. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  76612. __decorate([
  76613. BABYLON.serialize()
  76614. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  76615. __decorate([
  76616. BABYLON.serialize()
  76617. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  76618. __decorate([
  76619. BABYLON.serialize()
  76620. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  76621. __decorate([
  76622. BABYLON.serializeAsTexture("lensColorTexture")
  76623. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  76624. __decorate([
  76625. BABYLON.serialize()
  76626. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  76627. __decorate([
  76628. BABYLON.serialize()
  76629. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  76630. __decorate([
  76631. BABYLON.serialize()
  76632. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  76633. __decorate([
  76634. BABYLON.serialize()
  76635. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  76636. __decorate([
  76637. BABYLON.serializeAsTexture("lensStarTexture")
  76638. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  76639. __decorate([
  76640. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  76641. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  76642. __decorate([
  76643. BABYLON.serialize()
  76644. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  76645. __decorate([
  76646. BABYLON.serialize()
  76647. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  76648. __decorate([
  76649. BABYLON.serialize()
  76650. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  76651. __decorate([
  76652. BABYLON.serialize()
  76653. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  76654. __decorate([
  76655. BABYLON.serialize()
  76656. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  76657. __decorate([
  76658. BABYLON.serialize()
  76659. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  76660. __decorate([
  76661. BABYLON.serialize()
  76662. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  76663. __decorate([
  76664. BABYLON.serialize()
  76665. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  76666. __decorate([
  76667. BABYLON.serialize()
  76668. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  76669. __decorate([
  76670. BABYLON.serialize()
  76671. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  76672. __decorate([
  76673. BABYLON.serialize()
  76674. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  76675. __decorate([
  76676. BABYLON.serialize()
  76677. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  76678. return StandardRenderingPipeline;
  76679. }(BABYLON.PostProcessRenderPipeline));
  76680. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  76681. })(BABYLON || (BABYLON = {}));
  76682. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  76683. var BABYLON;
  76684. (function (BABYLON) {
  76685. var FxaaPostProcess = /** @class */ (function (_super) {
  76686. __extends(FxaaPostProcess, _super);
  76687. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76688. if (camera === void 0) { camera = null; }
  76689. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76690. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  76691. var defines = _this._getDefines();
  76692. _this.updateEffect(defines);
  76693. _this.onApplyObservable.add(function (effect) {
  76694. var texelSize = _this.texelSize;
  76695. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  76696. });
  76697. return _this;
  76698. }
  76699. FxaaPostProcess.prototype._getDefines = function () {
  76700. var engine = this.getEngine();
  76701. if (!engine) {
  76702. return null;
  76703. }
  76704. var glInfo = engine.getGlInfo();
  76705. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  76706. return "#define MALI 1\n";
  76707. }
  76708. return null;
  76709. };
  76710. return FxaaPostProcess;
  76711. }(BABYLON.PostProcess));
  76712. BABYLON.FxaaPostProcess = FxaaPostProcess;
  76713. })(BABYLON || (BABYLON = {}));
  76714. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  76715. var BABYLON;
  76716. (function (BABYLON) {
  76717. /**
  76718. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  76719. */
  76720. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  76721. __extends(ChromaticAberrationPostProcess, _super);
  76722. /**
  76723. * Creates a new instance ChromaticAberrationPostProcess
  76724. * @param name The name of the effect.
  76725. * @param screenWidth The width of the screen to apply the effect on.
  76726. * @param screenHeight The height of the screen to apply the effect on.
  76727. * @param options The required width/height ratio to downsize to before computing the render pass.
  76728. * @param camera The camera to apply the render pass to.
  76729. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76730. * @param engine The engine which the post process will be applied. (default: current engine)
  76731. * @param reusable If the post process can be reused on the same frame. (default: false)
  76732. * @param textureType Type of textures used when performing the post process. (default: 0)
  76733. * @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)
  76734. */
  76735. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76736. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76737. if (blockCompilation === void 0) { blockCompilation = false; }
  76738. 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;
  76739. /**
  76740. * The amount of seperation of rgb channels (default: 30)
  76741. */
  76742. _this.aberrationAmount = 30;
  76743. /**
  76744. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  76745. */
  76746. _this.radialIntensity = 0;
  76747. /**
  76748. * 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))
  76749. */
  76750. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  76751. /**
  76752. * 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))
  76753. */
  76754. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  76755. _this.onApplyObservable.add(function (effect) {
  76756. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  76757. effect.setFloat('screen_width', screenWidth);
  76758. effect.setFloat('screen_height', screenHeight);
  76759. effect.setFloat('radialIntensity', _this.radialIntensity);
  76760. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  76761. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  76762. });
  76763. return _this;
  76764. }
  76765. return ChromaticAberrationPostProcess;
  76766. }(BABYLON.PostProcess));
  76767. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  76768. })(BABYLON || (BABYLON = {}));
  76769. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  76770. var BABYLON;
  76771. (function (BABYLON) {
  76772. /**
  76773. * The GrainPostProcess adds noise to the image at mid luminance levels
  76774. */
  76775. var GrainPostProcess = /** @class */ (function (_super) {
  76776. __extends(GrainPostProcess, _super);
  76777. /**
  76778. * Creates a new instance of @see GrainPostProcess
  76779. * @param name The name of the effect.
  76780. * @param options The required width/height ratio to downsize to before computing the render pass.
  76781. * @param camera The camera to apply the render pass to.
  76782. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76783. * @param engine The engine which the post process will be applied. (default: current engine)
  76784. * @param reusable If the post process can be reused on the same frame. (default: false)
  76785. * @param textureType Type of textures used when performing the post process. (default: 0)
  76786. * @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)
  76787. */
  76788. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76789. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76790. if (blockCompilation === void 0) { blockCompilation = false; }
  76791. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76792. /**
  76793. * The intensity of the grain added (default: 30)
  76794. */
  76795. _this.intensity = 30;
  76796. /**
  76797. * If the grain should be randomized on every frame
  76798. */
  76799. _this.animated = false;
  76800. _this.onApplyObservable.add(function (effect) {
  76801. effect.setFloat('intensity', _this.intensity);
  76802. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  76803. });
  76804. return _this;
  76805. }
  76806. return GrainPostProcess;
  76807. }(BABYLON.PostProcess));
  76808. BABYLON.GrainPostProcess = GrainPostProcess;
  76809. })(BABYLON || (BABYLON = {}));
  76810. //# sourceMappingURL=babylon.grainPostProcess.js.map
  76811. var BABYLON;
  76812. (function (BABYLON) {
  76813. /**
  76814. * The SharpenPostProcess applies a sharpen kernel to every pixel
  76815. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76816. */
  76817. var SharpenPostProcess = /** @class */ (function (_super) {
  76818. __extends(SharpenPostProcess, _super);
  76819. /**
  76820. * Creates a new instance ConvolutionPostProcess
  76821. * @param name The name of the effect.
  76822. * @param options The required width/height ratio to downsize to before computing the render pass.
  76823. * @param camera The camera to apply the render pass to.
  76824. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76825. * @param engine The engine which the post process will be applied. (default: current engine)
  76826. * @param reusable If the post process can be reused on the same frame. (default: false)
  76827. * @param textureType Type of textures used when performing the post process. (default: 0)
  76828. * @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)
  76829. */
  76830. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76831. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76832. if (blockCompilation === void 0) { blockCompilation = false; }
  76833. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76834. /**
  76835. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  76836. */
  76837. _this.colorAmount = 1.0;
  76838. /**
  76839. * How much sharpness should be applied (default: 0.3)
  76840. */
  76841. _this.edgeAmount = 0.3;
  76842. _this.onApply = function (effect) {
  76843. effect.setFloat2("screenSize", _this.width, _this.height);
  76844. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  76845. };
  76846. return _this;
  76847. }
  76848. return SharpenPostProcess;
  76849. }(BABYLON.PostProcess));
  76850. BABYLON.SharpenPostProcess = SharpenPostProcess;
  76851. })(BABYLON || (BABYLON = {}));
  76852. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  76853. var BABYLON;
  76854. (function (BABYLON) {
  76855. /**
  76856. * The Blur Post Process which blurs an image based on a kernel and direction.
  76857. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  76858. */
  76859. var BlurPostProcess = /** @class */ (function (_super) {
  76860. __extends(BlurPostProcess, _super);
  76861. /**
  76862. * Creates a new instance BlurPostProcess
  76863. * @param name The name of the effect.
  76864. * @param direction The direction in which to blur the image.
  76865. * @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.
  76866. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  76867. * @param camera The camera to apply the render pass to.
  76868. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76869. * @param engine The engine which the post process will be applied. (default: current engine)
  76870. * @param reusable If the post process can be reused on the same frame. (default: false)
  76871. * @param textureType Type of textures used when performing the post process. (default: 0)
  76872. * @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)
  76873. */
  76874. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  76875. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76876. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76877. if (defines === void 0) { defines = ""; }
  76878. if (blockCompilation === void 0) { blockCompilation = false; }
  76879. 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;
  76880. _this.direction = direction;
  76881. _this.blockCompilation = blockCompilation;
  76882. _this._packedFloat = false;
  76883. _this._staticDefines = "";
  76884. _this._staticDefines = defines;
  76885. _this.onApplyObservable.add(function (effect) {
  76886. if (_this._outputTexture) {
  76887. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  76888. }
  76889. else {
  76890. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  76891. }
  76892. });
  76893. _this.kernel = kernel;
  76894. return _this;
  76895. }
  76896. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  76897. /**
  76898. * Gets the length in pixels of the blur sample region
  76899. */
  76900. get: function () {
  76901. return this._idealKernel;
  76902. },
  76903. /**
  76904. * Sets the length in pixels of the blur sample region
  76905. */
  76906. set: function (v) {
  76907. if (this._idealKernel === v) {
  76908. return;
  76909. }
  76910. v = Math.max(v, 1);
  76911. this._idealKernel = v;
  76912. this._kernel = this._nearestBestKernel(v);
  76913. if (!this.blockCompilation) {
  76914. this._updateParameters();
  76915. }
  76916. },
  76917. enumerable: true,
  76918. configurable: true
  76919. });
  76920. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  76921. /**
  76922. * Gets wether or not the blur is unpacking/repacking floats
  76923. */
  76924. get: function () {
  76925. return this._packedFloat;
  76926. },
  76927. /**
  76928. * Sets wether or not the blur needs to unpack/repack floats
  76929. */
  76930. set: function (v) {
  76931. if (this._packedFloat === v) {
  76932. return;
  76933. }
  76934. this._packedFloat = v;
  76935. if (!this.blockCompilation) {
  76936. this._updateParameters();
  76937. }
  76938. },
  76939. enumerable: true,
  76940. configurable: true
  76941. });
  76942. /**
  76943. * Updates the effect with the current post process compile time values and recompiles the shader.
  76944. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76945. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76946. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76947. * @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
  76948. * @param onCompiled Called when the shader has been compiled.
  76949. * @param onError Called if there is an error when compiling a shader.
  76950. */
  76951. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76952. if (defines === void 0) { defines = null; }
  76953. if (uniforms === void 0) { uniforms = null; }
  76954. if (samplers === void 0) { samplers = null; }
  76955. this._updateParameters(onCompiled, onError);
  76956. };
  76957. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  76958. // Generate sampling offsets and weights
  76959. var N = this._kernel;
  76960. var centerIndex = (N - 1) / 2;
  76961. // Generate Gaussian sampling weights over kernel
  76962. var offsets = [];
  76963. var weights = [];
  76964. var totalWeight = 0;
  76965. for (var i = 0; i < N; i++) {
  76966. var u = i / (N - 1);
  76967. var w = this._gaussianWeight(u * 2.0 - 1);
  76968. offsets[i] = (i - centerIndex);
  76969. weights[i] = w;
  76970. totalWeight += w;
  76971. }
  76972. // Normalize weights
  76973. for (var i = 0; i < weights.length; i++) {
  76974. weights[i] /= totalWeight;
  76975. }
  76976. // Optimize: combine samples to take advantage of hardware linear sampling
  76977. // Walk from left to center, combining pairs (symmetrically)
  76978. var linearSamplingWeights = [];
  76979. var linearSamplingOffsets = [];
  76980. var linearSamplingMap = [];
  76981. for (var i = 0; i <= centerIndex; i += 2) {
  76982. var j = Math.min(i + 1, Math.floor(centerIndex));
  76983. var singleCenterSample = i === j;
  76984. if (singleCenterSample) {
  76985. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76986. }
  76987. else {
  76988. var sharedCell = j === centerIndex;
  76989. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  76990. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  76991. if (offsetLinear === 0) {
  76992. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76993. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  76994. }
  76995. else {
  76996. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  76997. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  76998. }
  76999. }
  77000. }
  77001. for (var i = 0; i < linearSamplingMap.length; i++) {
  77002. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  77003. linearSamplingWeights[i] = linearSamplingMap[i].w;
  77004. }
  77005. // Replace with optimized
  77006. offsets = linearSamplingOffsets;
  77007. weights = linearSamplingWeights;
  77008. // Generate shaders
  77009. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  77010. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  77011. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  77012. var defines = "";
  77013. defines += this._staticDefines;
  77014. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  77015. if (this._staticDefines.indexOf("DOF") != -1) {
  77016. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  77017. varyingCount--;
  77018. }
  77019. for (var i = 0; i < varyingCount; i++) {
  77020. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  77021. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  77022. }
  77023. var depCount = 0;
  77024. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  77025. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  77026. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  77027. depCount++;
  77028. }
  77029. if (this.packedFloat) {
  77030. defines += "#define PACKEDFLOAT 1";
  77031. }
  77032. this.blockCompilation = false;
  77033. _super.prototype.updateEffect.call(this, defines, null, null, {
  77034. varyingCount: varyingCount,
  77035. depCount: depCount
  77036. }, onCompiled, onError);
  77037. };
  77038. /**
  77039. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  77040. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  77041. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  77042. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  77043. * The gaps between physical kernels are compensated for in the weighting of the samples
  77044. * @param idealKernel Ideal blur kernel.
  77045. * @return Nearest best kernel.
  77046. */
  77047. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  77048. var v = Math.round(idealKernel);
  77049. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  77050. var k = _a[_i];
  77051. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  77052. return Math.max(k, 3);
  77053. }
  77054. }
  77055. return Math.max(v, 3);
  77056. };
  77057. /**
  77058. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  77059. * @param x The point on the Gaussian distribution to sample.
  77060. * @return the value of the Gaussian function at x.
  77061. */
  77062. BlurPostProcess.prototype._gaussianWeight = function (x) {
  77063. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  77064. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  77065. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  77066. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  77067. // truncated at around 1.3% of peak strength.
  77068. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  77069. var sigma = (1 / 3);
  77070. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  77071. var exponent = -((x * x) / (2.0 * sigma * sigma));
  77072. var weight = (1.0 / denominator) * Math.exp(exponent);
  77073. return weight;
  77074. };
  77075. /**
  77076. * Generates a string that can be used as a floating point number in GLSL.
  77077. * @param x Value to print.
  77078. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  77079. * @return GLSL float string.
  77080. */
  77081. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  77082. if (decimalFigures === void 0) { decimalFigures = 8; }
  77083. return x.toFixed(decimalFigures).replace(/0+$/, '');
  77084. };
  77085. return BlurPostProcess;
  77086. }(BABYLON.PostProcess));
  77087. BABYLON.BlurPostProcess = BlurPostProcess;
  77088. })(BABYLON || (BABYLON = {}));
  77089. //# sourceMappingURL=babylon.blurPostProcess.js.map
  77090. var BABYLON;
  77091. (function (BABYLON) {
  77092. /**
  77093. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  77094. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  77095. * based on samples that have a large difference in distance than the center pixel.
  77096. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77097. */
  77098. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  77099. __extends(DepthOfFieldBlurPostProcess, _super);
  77100. /**
  77101. * Creates a new instance CircleOfConfusionPostProcess
  77102. * @param name The name of the effect.
  77103. * @param scene The scene the effect belongs to.
  77104. * @param direction The direction the blur should be applied.
  77105. * @param kernel The size of the kernel used to blur.
  77106. * @param options The required width/height ratio to downsize to before computing the render pass.
  77107. * @param camera The camera to apply the render pass to.
  77108. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  77109. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  77110. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77111. * @param engine The engine which the post process will be applied. (default: current engine)
  77112. * @param reusable If the post process can be reused on the same frame. (default: false)
  77113. * @param textureType Type of textures used when performing the post process. (default: 0)
  77114. * @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)
  77115. */
  77116. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  77117. if (imageToBlur === void 0) { imageToBlur = null; }
  77118. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77119. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77120. if (blockCompilation === void 0) { blockCompilation = false; }
  77121. 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;
  77122. _this.direction = direction;
  77123. _this.onApplyObservable.add(function (effect) {
  77124. if (imageToBlur != null) {
  77125. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  77126. }
  77127. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77128. if (scene.activeCamera) {
  77129. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  77130. }
  77131. });
  77132. return _this;
  77133. }
  77134. return DepthOfFieldBlurPostProcess;
  77135. }(BABYLON.BlurPostProcess));
  77136. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  77137. })(BABYLON || (BABYLON = {}));
  77138. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  77139. var BABYLON;
  77140. (function (BABYLON) {
  77141. /**
  77142. * Options to be set when merging outputs from the default pipeline.
  77143. */
  77144. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  77145. function DepthOfFieldMergePostProcessOptions() {
  77146. }
  77147. return DepthOfFieldMergePostProcessOptions;
  77148. }());
  77149. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  77150. /**
  77151. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77152. */
  77153. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  77154. __extends(DepthOfFieldMergePostProcess, _super);
  77155. /**
  77156. * Creates a new instance of DepthOfFieldMergePostProcess
  77157. * @param name The name of the effect.
  77158. * @param originalFromInput Post process which's input will be used for the merge.
  77159. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  77160. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  77161. * @param options The required width/height ratio to downsize to before computing the render pass.
  77162. * @param camera The camera to apply the render pass to.
  77163. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77164. * @param engine The engine which the post process will be applied. (default: current engine)
  77165. * @param reusable If the post process can be reused on the same frame. (default: false)
  77166. * @param textureType Type of textures used when performing the post process. (default: 0)
  77167. * @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)
  77168. */
  77169. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77170. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77171. if (blockCompilation === void 0) { blockCompilation = false; }
  77172. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77173. _this.blurSteps = blurSteps;
  77174. _this.onApplyObservable.add(function (effect) {
  77175. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77176. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77177. blurSteps.forEach(function (step, index) {
  77178. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  77179. });
  77180. });
  77181. if (!blockCompilation) {
  77182. _this.updateEffect();
  77183. }
  77184. return _this;
  77185. }
  77186. /**
  77187. * Updates the effect with the current post process compile time values and recompiles the shader.
  77188. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77189. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77190. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77191. * @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
  77192. * @param onCompiled Called when the shader has been compiled.
  77193. * @param onError Called if there is an error when compiling a shader.
  77194. */
  77195. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77196. if (defines === void 0) { defines = null; }
  77197. if (uniforms === void 0) { uniforms = null; }
  77198. if (samplers === void 0) { samplers = null; }
  77199. if (!defines) {
  77200. defines = "";
  77201. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  77202. }
  77203. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  77204. };
  77205. return DepthOfFieldMergePostProcess;
  77206. }(BABYLON.PostProcess));
  77207. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  77208. })(BABYLON || (BABYLON = {}));
  77209. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  77210. var BABYLON;
  77211. (function (BABYLON) {
  77212. /**
  77213. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  77214. */
  77215. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  77216. __extends(CircleOfConfusionPostProcess, _super);
  77217. /**
  77218. * Creates a new instance CircleOfConfusionPostProcess
  77219. * @param name The name of the effect.
  77220. * @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.
  77221. * @param options The required width/height ratio to downsize to before computing the render pass.
  77222. * @param camera The camera to apply the render pass to.
  77223. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77224. * @param engine The engine which the post process will be applied. (default: current engine)
  77225. * @param reusable If the post process can be reused on the same frame. (default: false)
  77226. * @param textureType Type of textures used when performing the post process. (default: 0)
  77227. * @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)
  77228. */
  77229. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77230. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77231. if (blockCompilation === void 0) { blockCompilation = false; }
  77232. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77233. /**
  77234. * 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.
  77235. */
  77236. _this.lensSize = 50;
  77237. /**
  77238. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77239. */
  77240. _this.fStop = 1.4;
  77241. /**
  77242. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77243. */
  77244. _this.focusDistance = 2000;
  77245. /**
  77246. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  77247. */
  77248. _this.focalLength = 50;
  77249. _this._depthTexture = null;
  77250. _this._depthTexture = depthTexture;
  77251. _this.onApplyObservable.add(function (effect) {
  77252. if (!_this._depthTexture) {
  77253. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  77254. return;
  77255. }
  77256. effect.setTexture("depthSampler", _this._depthTexture);
  77257. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  77258. var aperture = _this.lensSize / _this.fStop;
  77259. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  77260. effect.setFloat('focusDistance', _this.focusDistance);
  77261. effect.setFloat('cocPrecalculation', cocPrecalculation);
  77262. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  77263. });
  77264. return _this;
  77265. }
  77266. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  77267. /**
  77268. * 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.
  77269. */
  77270. set: function (value) {
  77271. this._depthTexture = value;
  77272. },
  77273. enumerable: true,
  77274. configurable: true
  77275. });
  77276. return CircleOfConfusionPostProcess;
  77277. }(BABYLON.PostProcess));
  77278. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  77279. })(BABYLON || (BABYLON = {}));
  77280. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  77281. var BABYLON;
  77282. (function (BABYLON) {
  77283. /**
  77284. * Specifies the level of max blur that should be applied when using the depth of field effect
  77285. */
  77286. var DepthOfFieldEffectBlurLevel;
  77287. (function (DepthOfFieldEffectBlurLevel) {
  77288. /**
  77289. * Subtle blur
  77290. */
  77291. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  77292. /**
  77293. * Medium blur
  77294. */
  77295. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  77296. /**
  77297. * Large blur
  77298. */
  77299. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  77300. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  77301. ;
  77302. /**
  77303. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  77304. */
  77305. var DepthOfFieldEffect = /** @class */ (function (_super) {
  77306. __extends(DepthOfFieldEffect, _super);
  77307. /**
  77308. * Creates a new instance DepthOfFieldEffect
  77309. * @param scene The scene the effect belongs to.
  77310. * @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.
  77311. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77312. * @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)
  77313. */
  77314. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  77315. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  77316. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77317. if (blockCompilation === void 0) { blockCompilation = false; }
  77318. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  77319. return _this._effects;
  77320. }, true) || this;
  77321. /**
  77322. * Internal post processes in depth of field effect
  77323. */
  77324. _this._effects = [];
  77325. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  77326. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77327. // 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)
  77328. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  77329. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77330. _this._depthOfFieldBlurY = [];
  77331. _this._depthOfFieldBlurX = [];
  77332. var blurCount = 1;
  77333. var kernelSize = 15;
  77334. switch (blurLevel) {
  77335. case DepthOfFieldEffectBlurLevel.High: {
  77336. blurCount = 3;
  77337. kernelSize = 51;
  77338. break;
  77339. }
  77340. case DepthOfFieldEffectBlurLevel.Medium: {
  77341. blurCount = 2;
  77342. kernelSize = 31;
  77343. break;
  77344. }
  77345. default: {
  77346. kernelSize = 15;
  77347. blurCount = 1;
  77348. break;
  77349. }
  77350. }
  77351. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  77352. var ratio = 1.0;
  77353. for (var i = 0; i < blurCount; i++) {
  77354. 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);
  77355. blurY.autoClear = false;
  77356. ratio = 0.75 / Math.pow(2, i);
  77357. 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);
  77358. blurX.autoClear = false;
  77359. _this._depthOfFieldBlurY.push(blurY);
  77360. _this._depthOfFieldBlurX.push(blurX);
  77361. }
  77362. // Set all post processes on the effect.
  77363. _this._effects = [_this._circleOfConfusion];
  77364. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  77365. _this._effects.push(_this._depthOfFieldBlurY[i]);
  77366. _this._effects.push(_this._depthOfFieldBlurX[i]);
  77367. }
  77368. // Merge blurred images with original image based on circleOfConfusion
  77369. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77370. _this._dofMerge.autoClear = false;
  77371. _this._effects.push(_this._dofMerge);
  77372. return _this;
  77373. }
  77374. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  77375. get: function () {
  77376. return this._circleOfConfusion.focalLength;
  77377. },
  77378. /**
  77379. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  77380. */
  77381. set: function (value) {
  77382. this._circleOfConfusion.focalLength = value;
  77383. },
  77384. enumerable: true,
  77385. configurable: true
  77386. });
  77387. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  77388. get: function () {
  77389. return this._circleOfConfusion.fStop;
  77390. },
  77391. /**
  77392. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77393. */
  77394. set: function (value) {
  77395. this._circleOfConfusion.fStop = value;
  77396. },
  77397. enumerable: true,
  77398. configurable: true
  77399. });
  77400. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  77401. get: function () {
  77402. return this._circleOfConfusion.focusDistance;
  77403. },
  77404. /**
  77405. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77406. */
  77407. set: function (value) {
  77408. this._circleOfConfusion.focusDistance = value;
  77409. },
  77410. enumerable: true,
  77411. configurable: true
  77412. });
  77413. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  77414. get: function () {
  77415. return this._circleOfConfusion.lensSize;
  77416. },
  77417. /**
  77418. * 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.
  77419. */
  77420. set: function (value) {
  77421. this._circleOfConfusion.lensSize = value;
  77422. },
  77423. enumerable: true,
  77424. configurable: true
  77425. });
  77426. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  77427. /**
  77428. * 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.
  77429. */
  77430. set: function (value) {
  77431. this._circleOfConfusion.depthTexture = value;
  77432. },
  77433. enumerable: true,
  77434. configurable: true
  77435. });
  77436. /**
  77437. * Disposes each of the internal effects for a given camera.
  77438. * @param camera The camera to dispose the effect on.
  77439. */
  77440. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  77441. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77442. this._effects[effectIndex].dispose(camera);
  77443. }
  77444. };
  77445. /**
  77446. * Internal
  77447. */
  77448. DepthOfFieldEffect.prototype._updateEffects = function () {
  77449. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77450. this._effects[effectIndex].updateEffect();
  77451. }
  77452. };
  77453. /**
  77454. * Internal
  77455. * @returns if all the contained post processes are ready.
  77456. */
  77457. DepthOfFieldEffect.prototype._isReady = function () {
  77458. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77459. if (!this._effects[effectIndex].isReady()) {
  77460. return false;
  77461. }
  77462. }
  77463. return true;
  77464. };
  77465. return DepthOfFieldEffect;
  77466. }(BABYLON.PostProcessRenderEffect));
  77467. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  77468. })(BABYLON || (BABYLON = {}));
  77469. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  77470. var BABYLON;
  77471. (function (BABYLON) {
  77472. /**
  77473. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77474. */
  77475. var BloomMergePostProcess = /** @class */ (function (_super) {
  77476. __extends(BloomMergePostProcess, _super);
  77477. /**
  77478. * Creates a new instance of @see BloomMergePostProcess
  77479. * @param name The name of the effect.
  77480. * @param originalFromInput Post process which's input will be used for the merge.
  77481. * @param blurred Blurred highlights post process which's output will be used.
  77482. * @param weight Weight of the bloom to be added to the original input.
  77483. * @param options The required width/height ratio to downsize to before computing the render pass.
  77484. * @param camera The camera to apply the render pass to.
  77485. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77486. * @param engine The engine which the post process will be applied. (default: current engine)
  77487. * @param reusable If the post process can be reused on the same frame. (default: false)
  77488. * @param textureType Type of textures used when performing the post process. (default: 0)
  77489. * @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)
  77490. */
  77491. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77492. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77493. if (blockCompilation === void 0) { blockCompilation = false; }
  77494. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77495. _this.weight = weight;
  77496. _this.onApplyObservable.add(function (effect) {
  77497. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77498. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  77499. effect.setFloat("bloomWeight", _this.weight);
  77500. });
  77501. if (!blockCompilation) {
  77502. _this.updateEffect();
  77503. }
  77504. return _this;
  77505. }
  77506. return BloomMergePostProcess;
  77507. }(BABYLON.PostProcess));
  77508. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  77509. })(BABYLON || (BABYLON = {}));
  77510. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  77511. var BABYLON;
  77512. (function (BABYLON) {
  77513. /**
  77514. * 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.
  77515. */
  77516. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  77517. __extends(ExtractHighlightsPostProcess, _super);
  77518. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77519. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77520. if (blockCompilation === void 0) { blockCompilation = false; }
  77521. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77522. /**
  77523. * The luminance threshold, pixels below this value will be set to black.
  77524. */
  77525. _this.threshold = 0.9;
  77526. /**
  77527. * Internal
  77528. */
  77529. _this._exposure = 1;
  77530. /**
  77531. * Post process which has the input texture to be used when performing highlight extraction
  77532. */
  77533. _this._inputPostProcess = null;
  77534. _this.onApplyObservable.add(function (effect) {
  77535. if (_this._inputPostProcess) {
  77536. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  77537. }
  77538. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  77539. effect.setFloat('exposure', _this._exposure);
  77540. });
  77541. return _this;
  77542. }
  77543. return ExtractHighlightsPostProcess;
  77544. }(BABYLON.PostProcess));
  77545. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  77546. })(BABYLON || (BABYLON = {}));
  77547. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  77548. var BABYLON;
  77549. (function (BABYLON) {
  77550. /**
  77551. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  77552. */
  77553. var BloomEffect = /** @class */ (function (_super) {
  77554. __extends(BloomEffect, _super);
  77555. /**
  77556. * Creates a new instance of @see BloomEffect
  77557. * @param scene The scene the effect belongs to.
  77558. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  77559. * @param bloomKernel The size of the kernel to be used when applying the blur.
  77560. * @param bloomWeight The the strength of bloom.
  77561. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77562. * @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)
  77563. */
  77564. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  77565. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77566. if (blockCompilation === void 0) { blockCompilation = false; }
  77567. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  77568. return _this._effects;
  77569. }, true) || this;
  77570. _this.bloomScale = bloomScale;
  77571. /**
  77572. * Internal
  77573. */
  77574. _this._effects = [];
  77575. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77576. _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);
  77577. _this._blurX.alwaysForcePOT = true;
  77578. _this._blurX.autoClear = false;
  77579. _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);
  77580. _this._blurY.alwaysForcePOT = true;
  77581. _this._blurY.autoClear = false;
  77582. _this.kernel = bloomKernel;
  77583. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  77584. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77585. _this._merge.autoClear = false;
  77586. _this._effects.push(_this._merge);
  77587. return _this;
  77588. }
  77589. Object.defineProperty(BloomEffect.prototype, "threshold", {
  77590. /**
  77591. * The luminance threshold to find bright areas of the image to bloom.
  77592. */
  77593. get: function () {
  77594. return this._downscale.threshold;
  77595. },
  77596. set: function (value) {
  77597. this._downscale.threshold = value;
  77598. },
  77599. enumerable: true,
  77600. configurable: true
  77601. });
  77602. Object.defineProperty(BloomEffect.prototype, "weight", {
  77603. /**
  77604. * The strength of the bloom.
  77605. */
  77606. get: function () {
  77607. return this._merge.weight;
  77608. },
  77609. set: function (value) {
  77610. this._merge.weight = value;
  77611. },
  77612. enumerable: true,
  77613. configurable: true
  77614. });
  77615. Object.defineProperty(BloomEffect.prototype, "kernel", {
  77616. /**
  77617. * Specifies the size of the bloom blur kernel, relative to the final output size
  77618. */
  77619. get: function () {
  77620. return this._blurX.kernel / this.bloomScale;
  77621. },
  77622. set: function (value) {
  77623. this._blurX.kernel = value * this.bloomScale;
  77624. this._blurY.kernel = value * this.bloomScale;
  77625. },
  77626. enumerable: true,
  77627. configurable: true
  77628. });
  77629. /**
  77630. * Disposes each of the internal effects for a given camera.
  77631. * @param camera The camera to dispose the effect on.
  77632. */
  77633. BloomEffect.prototype.disposeEffects = function (camera) {
  77634. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77635. this._effects[effectIndex].dispose(camera);
  77636. }
  77637. };
  77638. /**
  77639. * Internal
  77640. */
  77641. BloomEffect.prototype._updateEffects = function () {
  77642. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77643. this._effects[effectIndex].updateEffect();
  77644. }
  77645. };
  77646. /**
  77647. * Internal
  77648. * @returns if all the contained post processes are ready.
  77649. */
  77650. BloomEffect.prototype._isReady = function () {
  77651. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77652. if (!this._effects[effectIndex].isReady()) {
  77653. return false;
  77654. }
  77655. }
  77656. return true;
  77657. };
  77658. return BloomEffect;
  77659. }(BABYLON.PostProcessRenderEffect));
  77660. BABYLON.BloomEffect = BloomEffect;
  77661. })(BABYLON || (BABYLON = {}));
  77662. //# sourceMappingURL=babylon.bloomEffect.js.map
  77663. var BABYLON;
  77664. (function (BABYLON) {
  77665. /**
  77666. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  77667. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  77668. */
  77669. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  77670. __extends(DefaultRenderingPipeline, _super);
  77671. /**
  77672. * @constructor
  77673. * @param {string} name - The rendering pipeline name (default: "")
  77674. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  77675. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  77676. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  77677. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  77678. */
  77679. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  77680. if (name === void 0) { name = ""; }
  77681. if (hdr === void 0) { hdr = true; }
  77682. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77683. if (automaticBuild === void 0) { automaticBuild = true; }
  77684. var _this = _super.call(this, scene.getEngine(), name) || this;
  77685. _this._camerasToBeAttached = [];
  77686. /**
  77687. * ID of the sharpen post process,
  77688. */
  77689. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  77690. /**
  77691. * ID of the image processing post process;
  77692. */
  77693. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  77694. /**
  77695. * ID of the Fast Approximate Anti-Aliasing post process;
  77696. */
  77697. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  77698. /**
  77699. * ID of the chromatic aberration post process,
  77700. */
  77701. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  77702. /**
  77703. * ID of the grain post process
  77704. */
  77705. _this.GrainPostProcessId = "GrainPostProcessEffect";
  77706. /**
  77707. * Glow post process which adds a glow to emmisive areas of the image
  77708. */
  77709. _this._glowLayer = null;
  77710. /**
  77711. * Animations which can be used to tweak settings over a period of time
  77712. */
  77713. _this.animations = [];
  77714. _this._imageProcessingConfigurationObserver = null;
  77715. // Values
  77716. _this._sharpenEnabled = false;
  77717. _this._bloomEnabled = false;
  77718. _this._depthOfFieldEnabled = false;
  77719. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  77720. _this._fxaaEnabled = false;
  77721. _this._imageProcessingEnabled = true;
  77722. _this._bloomScale = 0.5;
  77723. _this._chromaticAberrationEnabled = false;
  77724. _this._grainEnabled = false;
  77725. _this._buildAllowed = true;
  77726. _this._resizeObserver = null;
  77727. _this._hardwareScaleLevel = 1.0;
  77728. _this._bloomKernel = 64;
  77729. /**
  77730. * Specifies the weight of the bloom in the final rendering
  77731. */
  77732. _this._bloomWeight = 0.15;
  77733. /**
  77734. * Specifies the luma threshold for the area that will be blurred by the bloom
  77735. */
  77736. _this._bloomThreshold = 0.9;
  77737. _this._samples = 1;
  77738. _this._hasCleared = false;
  77739. _this._prevPostProcess = null;
  77740. _this._prevPrevPostProcess = null;
  77741. _this._cameras = cameras || scene.cameras;
  77742. _this._camerasToBeAttached = _this._cameras.slice();
  77743. _this._buildAllowed = automaticBuild;
  77744. // Initialize
  77745. _this._scene = scene;
  77746. var caps = _this._scene.getEngine().getCaps();
  77747. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  77748. // Misc
  77749. if (_this._hdr) {
  77750. if (caps.textureHalfFloatRender) {
  77751. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77752. }
  77753. else if (caps.textureFloatRender) {
  77754. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77755. }
  77756. }
  77757. else {
  77758. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77759. }
  77760. // Attach
  77761. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77762. var engine = _this._scene.getEngine();
  77763. // Create post processes before hand so they can be modified before enabled.
  77764. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  77765. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77766. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  77767. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  77768. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  77769. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77770. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  77771. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77772. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  77773. _this._resizeObserver = engine.onResizeObservable.add(function () {
  77774. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  77775. _this.bloomKernel = _this.bloomKernel;
  77776. });
  77777. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  77778. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  77779. });
  77780. _this._buildPipeline();
  77781. return _this;
  77782. }
  77783. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  77784. get: function () {
  77785. return this._sharpenEnabled;
  77786. },
  77787. /**
  77788. * Enable or disable the sharpen process from the pipeline
  77789. */
  77790. set: function (enabled) {
  77791. if (this._sharpenEnabled === enabled) {
  77792. return;
  77793. }
  77794. this._sharpenEnabled = enabled;
  77795. this._buildPipeline();
  77796. },
  77797. enumerable: true,
  77798. configurable: true
  77799. });
  77800. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  77801. /**
  77802. * Specifies the size of the bloom blur kernel, relative to the final output size
  77803. */
  77804. get: function () {
  77805. return this._bloomKernel;
  77806. },
  77807. set: function (value) {
  77808. this._bloomKernel = value;
  77809. this.bloom.kernel = value / this._hardwareScaleLevel;
  77810. },
  77811. enumerable: true,
  77812. configurable: true
  77813. });
  77814. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  77815. get: function () {
  77816. return this._bloomWeight;
  77817. },
  77818. /**
  77819. * The strength of the bloom.
  77820. */
  77821. set: function (value) {
  77822. if (this._bloomWeight === value) {
  77823. return;
  77824. }
  77825. this.bloom.weight = value;
  77826. this._bloomWeight = value;
  77827. },
  77828. enumerable: true,
  77829. configurable: true
  77830. });
  77831. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  77832. get: function () {
  77833. return this._bloomThreshold;
  77834. },
  77835. /**
  77836. * The strength of the bloom.
  77837. */
  77838. set: function (value) {
  77839. if (this._bloomThreshold === value) {
  77840. return;
  77841. }
  77842. this.bloom.threshold = value;
  77843. this._bloomThreshold = value;
  77844. },
  77845. enumerable: true,
  77846. configurable: true
  77847. });
  77848. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  77849. get: function () {
  77850. return this._bloomScale;
  77851. },
  77852. /**
  77853. * The scale of the bloom, lower value will provide better performance.
  77854. */
  77855. set: function (value) {
  77856. if (this._bloomScale === value) {
  77857. return;
  77858. }
  77859. this._bloomScale = value;
  77860. // recreate bloom and dispose old as this setting is not dynamic
  77861. this._rebuildBloom();
  77862. this._buildPipeline();
  77863. },
  77864. enumerable: true,
  77865. configurable: true
  77866. });
  77867. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  77868. get: function () {
  77869. return this._bloomEnabled;
  77870. },
  77871. /**
  77872. * Enable or disable the bloom from the pipeline
  77873. */
  77874. set: function (enabled) {
  77875. if (this._bloomEnabled === enabled) {
  77876. return;
  77877. }
  77878. this._bloomEnabled = enabled;
  77879. this._buildPipeline();
  77880. },
  77881. enumerable: true,
  77882. configurable: true
  77883. });
  77884. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  77885. // recreate bloom and dispose old as this setting is not dynamic
  77886. var oldBloom = this.bloom;
  77887. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  77888. this.bloom.threshold = oldBloom.threshold;
  77889. for (var i = 0; i < this._cameras.length; i++) {
  77890. oldBloom.disposeEffects(this._cameras[i]);
  77891. }
  77892. };
  77893. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  77894. /**
  77895. * If the depth of field is enabled.
  77896. */
  77897. get: function () {
  77898. return this._depthOfFieldEnabled;
  77899. },
  77900. set: function (enabled) {
  77901. if (this._depthOfFieldEnabled === enabled) {
  77902. return;
  77903. }
  77904. this._depthOfFieldEnabled = enabled;
  77905. this._buildPipeline();
  77906. },
  77907. enumerable: true,
  77908. configurable: true
  77909. });
  77910. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  77911. /**
  77912. * Blur level of the depth of field effect. (Higher blur will effect performance)
  77913. */
  77914. get: function () {
  77915. return this._depthOfFieldBlurLevel;
  77916. },
  77917. set: function (value) {
  77918. if (this._depthOfFieldBlurLevel === value) {
  77919. return;
  77920. }
  77921. this._depthOfFieldBlurLevel = value;
  77922. // recreate dof and dispose old as this setting is not dynamic
  77923. var oldDof = this.depthOfField;
  77924. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  77925. this.depthOfField.focalLength = oldDof.focalLength;
  77926. this.depthOfField.focusDistance = oldDof.focusDistance;
  77927. this.depthOfField.fStop = oldDof.fStop;
  77928. this.depthOfField.lensSize = oldDof.lensSize;
  77929. for (var i = 0; i < this._cameras.length; i++) {
  77930. oldDof.disposeEffects(this._cameras[i]);
  77931. }
  77932. this._buildPipeline();
  77933. },
  77934. enumerable: true,
  77935. configurable: true
  77936. });
  77937. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  77938. get: function () {
  77939. return this._fxaaEnabled;
  77940. },
  77941. /**
  77942. * If the anti aliasing is enabled.
  77943. */
  77944. set: function (enabled) {
  77945. if (this._fxaaEnabled === enabled) {
  77946. return;
  77947. }
  77948. this._fxaaEnabled = enabled;
  77949. this._buildPipeline();
  77950. },
  77951. enumerable: true,
  77952. configurable: true
  77953. });
  77954. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  77955. get: function () {
  77956. return this._samples;
  77957. },
  77958. /**
  77959. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  77960. */
  77961. set: function (sampleCount) {
  77962. if (this._samples === sampleCount) {
  77963. return;
  77964. }
  77965. this._samples = sampleCount;
  77966. this._buildPipeline();
  77967. },
  77968. enumerable: true,
  77969. configurable: true
  77970. });
  77971. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  77972. get: function () {
  77973. return this._imageProcessingEnabled;
  77974. },
  77975. /**
  77976. * If image processing is enabled.
  77977. */
  77978. set: function (enabled) {
  77979. if (this._imageProcessingEnabled === enabled) {
  77980. return;
  77981. }
  77982. this._imageProcessingEnabled = enabled;
  77983. this._buildPipeline();
  77984. },
  77985. enumerable: true,
  77986. configurable: true
  77987. });
  77988. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  77989. get: function () {
  77990. return this._glowLayer == null;
  77991. },
  77992. /**
  77993. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  77994. */
  77995. set: function (enabled) {
  77996. if (enabled && !this._glowLayer) {
  77997. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  77998. }
  77999. else if (!enabled && this._glowLayer) {
  78000. this._glowLayer.dispose();
  78001. this._glowLayer = null;
  78002. }
  78003. },
  78004. enumerable: true,
  78005. configurable: true
  78006. });
  78007. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  78008. get: function () {
  78009. return this._chromaticAberrationEnabled;
  78010. },
  78011. /**
  78012. * Enable or disable the chromaticAberration process from the pipeline
  78013. */
  78014. set: function (enabled) {
  78015. if (this._chromaticAberrationEnabled === enabled) {
  78016. return;
  78017. }
  78018. this._chromaticAberrationEnabled = enabled;
  78019. this._buildPipeline();
  78020. },
  78021. enumerable: true,
  78022. configurable: true
  78023. });
  78024. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  78025. get: function () {
  78026. return this._grainEnabled;
  78027. },
  78028. /**
  78029. * Enable or disable the grain process from the pipeline
  78030. */
  78031. set: function (enabled) {
  78032. if (this._grainEnabled === enabled) {
  78033. return;
  78034. }
  78035. this._grainEnabled = enabled;
  78036. this._buildPipeline();
  78037. },
  78038. enumerable: true,
  78039. configurable: true
  78040. });
  78041. /**
  78042. * Force the compilation of the entire pipeline.
  78043. */
  78044. DefaultRenderingPipeline.prototype.prepare = function () {
  78045. var previousState = this._buildAllowed;
  78046. this._buildAllowed = true;
  78047. this._buildPipeline();
  78048. this._buildAllowed = previousState;
  78049. };
  78050. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  78051. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  78052. if (this._hasCleared) {
  78053. postProcess.autoClear = false;
  78054. }
  78055. else {
  78056. postProcess.autoClear = true;
  78057. this._scene.autoClear = false;
  78058. this._hasCleared = true;
  78059. }
  78060. if (!skipTextureSharing) {
  78061. if (this._prevPrevPostProcess) {
  78062. postProcess.shareOutputWith(this._prevPrevPostProcess);
  78063. }
  78064. else {
  78065. postProcess.useOwnOutput();
  78066. }
  78067. if (this._prevPostProcess) {
  78068. this._prevPrevPostProcess = this._prevPostProcess;
  78069. }
  78070. this._prevPostProcess = postProcess;
  78071. }
  78072. };
  78073. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  78074. var _this = this;
  78075. if (!this._buildAllowed) {
  78076. return;
  78077. }
  78078. this._scene.autoClear = true;
  78079. var engine = this._scene.getEngine();
  78080. this._disposePostProcesses();
  78081. if (this._cameras !== null) {
  78082. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78083. // get back cameras to be used to reattach pipeline
  78084. this._cameras = this._camerasToBeAttached.slice();
  78085. }
  78086. this._reset();
  78087. this._prevPostProcess = null;
  78088. this._prevPrevPostProcess = null;
  78089. this._hasCleared = false;
  78090. if (this.depthOfFieldEnabled) {
  78091. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  78092. this.depthOfField.depthTexture = depthTexture;
  78093. if (!this.depthOfField._isReady()) {
  78094. this.depthOfField._updateEffects();
  78095. }
  78096. this.addEffect(this.depthOfField);
  78097. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  78098. }
  78099. if (this.bloomEnabled) {
  78100. if (!this.bloom._isReady()) {
  78101. this.bloom._updateEffects();
  78102. }
  78103. this.addEffect(this.bloom);
  78104. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  78105. }
  78106. if (this._imageProcessingEnabled) {
  78107. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78108. if (this._hdr) {
  78109. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  78110. this._setAutoClearAndTextureSharing(this.imageProcessing);
  78111. }
  78112. else {
  78113. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  78114. }
  78115. }
  78116. if (this.sharpenEnabled) {
  78117. if (!this.sharpen.isReady()) {
  78118. this.sharpen.updateEffect();
  78119. }
  78120. this.addEffect(this._sharpenEffect);
  78121. this._setAutoClearAndTextureSharing(this.sharpen);
  78122. }
  78123. if (this.grainEnabled) {
  78124. if (!this.grain.isReady()) {
  78125. this.grain.updateEffect();
  78126. }
  78127. this.addEffect(this._grainEffect);
  78128. this._setAutoClearAndTextureSharing(this.grain);
  78129. }
  78130. if (this.chromaticAberrationEnabled) {
  78131. if (!this.chromaticAberration.isReady()) {
  78132. this.chromaticAberration.updateEffect();
  78133. }
  78134. this.addEffect(this._chromaticAberrationEffect);
  78135. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  78136. }
  78137. if (this.fxaaEnabled) {
  78138. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78139. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  78140. this._setAutoClearAndTextureSharing(this.fxaa, true);
  78141. }
  78142. if (this._cameras !== null) {
  78143. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78144. }
  78145. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  78146. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  78147. }
  78148. };
  78149. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  78150. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  78151. for (var i = 0; i < this._cameras.length; i++) {
  78152. var camera = this._cameras[i];
  78153. if (this.imageProcessing) {
  78154. this.imageProcessing.dispose(camera);
  78155. }
  78156. if (this.fxaa) {
  78157. this.fxaa.dispose(camera);
  78158. }
  78159. // These are created in the constructor and should not be disposed on every pipeline change
  78160. if (disposeNonRecreated) {
  78161. if (this.sharpen) {
  78162. this.sharpen.dispose(camera);
  78163. }
  78164. if (this.depthOfField) {
  78165. this.depthOfField.disposeEffects(camera);
  78166. }
  78167. if (this.bloom) {
  78168. this.bloom.disposeEffects(camera);
  78169. }
  78170. if (this.chromaticAberration) {
  78171. this.chromaticAberration.dispose(camera);
  78172. }
  78173. if (this.grain) {
  78174. this.grain.dispose(camera);
  78175. }
  78176. if (this._glowLayer) {
  78177. this._glowLayer.dispose();
  78178. }
  78179. }
  78180. }
  78181. this.imageProcessing = null;
  78182. this.fxaa = null;
  78183. if (disposeNonRecreated) {
  78184. this.sharpen = null;
  78185. this._sharpenEffect = null;
  78186. this.depthOfField = null;
  78187. this.bloom = null;
  78188. this.chromaticAberration = null;
  78189. this._chromaticAberrationEffect = null;
  78190. this.grain = null;
  78191. this._grainEffect = null;
  78192. this._glowLayer = null;
  78193. }
  78194. };
  78195. /**
  78196. * Adds a camera to the pipeline
  78197. * @param camera the camera to be added
  78198. */
  78199. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  78200. this._camerasToBeAttached.push(camera);
  78201. this._buildPipeline();
  78202. };
  78203. /**
  78204. * Removes a camera from the pipeline
  78205. * @param camera the camera to remove
  78206. */
  78207. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  78208. var index = this._camerasToBeAttached.indexOf(camera);
  78209. this._camerasToBeAttached.splice(index, 1);
  78210. this._buildPipeline();
  78211. };
  78212. /**
  78213. * Dispose of the pipeline and stop all post processes
  78214. */
  78215. DefaultRenderingPipeline.prototype.dispose = function () {
  78216. this._disposePostProcesses(true);
  78217. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78218. this._scene.autoClear = true;
  78219. if (this._resizeObserver) {
  78220. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  78221. this._resizeObserver = null;
  78222. }
  78223. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  78224. _super.prototype.dispose.call(this);
  78225. };
  78226. /**
  78227. * Serialize the rendering pipeline (Used when exporting)
  78228. * @returns the serialized object
  78229. */
  78230. DefaultRenderingPipeline.prototype.serialize = function () {
  78231. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78232. serializationObject.customType = "DefaultRenderingPipeline";
  78233. return serializationObject;
  78234. };
  78235. /**
  78236. * Parse the serialized pipeline
  78237. * @param source Source pipeline.
  78238. * @param scene The scene to load the pipeline to.
  78239. * @param rootUrl The URL of the serialized pipeline.
  78240. * @returns An instantiated pipeline from the serialized object.
  78241. */
  78242. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78243. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  78244. };
  78245. __decorate([
  78246. BABYLON.serialize()
  78247. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  78248. __decorate([
  78249. BABYLON.serialize()
  78250. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  78251. __decorate([
  78252. BABYLON.serialize()
  78253. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  78254. __decorate([
  78255. BABYLON.serialize()
  78256. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  78257. __decorate([
  78258. BABYLON.serialize()
  78259. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  78260. __decorate([
  78261. BABYLON.serialize()
  78262. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  78263. __decorate([
  78264. BABYLON.serialize()
  78265. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  78266. __decorate([
  78267. BABYLON.serialize()
  78268. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  78269. __decorate([
  78270. BABYLON.serialize()
  78271. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  78272. __decorate([
  78273. BABYLON.serialize()
  78274. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  78275. __decorate([
  78276. BABYLON.serialize()
  78277. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  78278. __decorate([
  78279. BABYLON.serialize()
  78280. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  78281. __decorate([
  78282. BABYLON.serialize()
  78283. ], DefaultRenderingPipeline.prototype, "samples", null);
  78284. __decorate([
  78285. BABYLON.serialize()
  78286. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  78287. __decorate([
  78288. BABYLON.serialize()
  78289. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  78290. __decorate([
  78291. BABYLON.serialize()
  78292. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  78293. __decorate([
  78294. BABYLON.serialize()
  78295. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  78296. return DefaultRenderingPipeline;
  78297. }(BABYLON.PostProcessRenderPipeline));
  78298. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  78299. })(BABYLON || (BABYLON = {}));
  78300. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  78301. var BABYLON;
  78302. (function (BABYLON) {
  78303. /**
  78304. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78305. */
  78306. var GeometryBufferRenderer = /** @class */ (function () {
  78307. /**
  78308. * Creates a new G Buffer for the scene
  78309. * @param scene The scene the buffer belongs to
  78310. * @param ratio How big is the buffer related to the main canvas.
  78311. */
  78312. function GeometryBufferRenderer(scene, ratio) {
  78313. if (ratio === void 0) { ratio = 1; }
  78314. this._enablePosition = false;
  78315. this._scene = scene;
  78316. this._ratio = ratio;
  78317. // Render target
  78318. this._createRenderTargets();
  78319. }
  78320. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78321. /**
  78322. * Set the render list (meshes to be rendered) used in the G buffer.
  78323. */
  78324. set: function (meshes) {
  78325. this._multiRenderTarget.renderList = meshes;
  78326. },
  78327. enumerable: true,
  78328. configurable: true
  78329. });
  78330. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78331. /**
  78332. * Gets wether or not G buffer are supported by the running hardware.
  78333. * This requires draw buffer supports
  78334. */
  78335. get: function () {
  78336. return this._multiRenderTarget.isSupported;
  78337. },
  78338. enumerable: true,
  78339. configurable: true
  78340. });
  78341. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78342. /**
  78343. * Gets wether or not position are enabled for the G buffer.
  78344. */
  78345. get: function () {
  78346. return this._enablePosition;
  78347. },
  78348. /**
  78349. * Sets wether or not position are enabled for the G buffer.
  78350. */
  78351. set: function (enable) {
  78352. this._enablePosition = enable;
  78353. this.dispose();
  78354. this._createRenderTargets();
  78355. },
  78356. enumerable: true,
  78357. configurable: true
  78358. });
  78359. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78360. /**
  78361. * Gets the scene associated with the buffer.
  78362. */
  78363. get: function () {
  78364. return this._scene;
  78365. },
  78366. enumerable: true,
  78367. configurable: true
  78368. });
  78369. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78370. /**
  78371. * Gets the ratio used by the buffer during its creation.
  78372. * How big is the buffer related to the main canvas.
  78373. */
  78374. get: function () {
  78375. return this._ratio;
  78376. },
  78377. enumerable: true,
  78378. configurable: true
  78379. });
  78380. /**
  78381. * Checks wether everything is ready to render a submesh to the G buffer.
  78382. * @param subMesh the submesh to check readiness for
  78383. * @param useInstances is the mesh drawn using instance or not
  78384. * @returns true if ready otherwise false
  78385. */
  78386. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78387. var material = subMesh.getMaterial();
  78388. if (material && material.disableDepthWrite) {
  78389. return false;
  78390. }
  78391. var defines = [];
  78392. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78393. var mesh = subMesh.getMesh();
  78394. // Alpha test
  78395. if (material && material.needAlphaTesting()) {
  78396. defines.push("#define ALPHATEST");
  78397. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78398. attribs.push(BABYLON.VertexBuffer.UVKind);
  78399. defines.push("#define UV1");
  78400. }
  78401. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78402. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78403. defines.push("#define UV2");
  78404. }
  78405. }
  78406. // Buffers
  78407. if (this._enablePosition) {
  78408. defines.push("#define POSITION");
  78409. }
  78410. // Bones
  78411. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78412. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78413. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78414. if (mesh.numBoneInfluencers > 4) {
  78415. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78416. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78417. }
  78418. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78419. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78420. }
  78421. else {
  78422. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78423. }
  78424. // Instances
  78425. if (useInstances) {
  78426. defines.push("#define INSTANCES");
  78427. attribs.push("world0");
  78428. attribs.push("world1");
  78429. attribs.push("world2");
  78430. attribs.push("world3");
  78431. }
  78432. // Get correct effect
  78433. var join = defines.join("\n");
  78434. if (this._cachedDefines !== join) {
  78435. this._cachedDefines = join;
  78436. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78437. }
  78438. return this._effect.isReady();
  78439. };
  78440. /**
  78441. * Gets the current underlying G Buffer.
  78442. * @returns the buffer
  78443. */
  78444. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78445. return this._multiRenderTarget;
  78446. };
  78447. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78448. /**
  78449. * Gets the number of samples used to render the buffer (anti aliasing).
  78450. */
  78451. get: function () {
  78452. return this._multiRenderTarget.samples;
  78453. },
  78454. /**
  78455. * Sets the number of samples used to render the buffer (anti aliasing).
  78456. */
  78457. set: function (value) {
  78458. this._multiRenderTarget.samples = value;
  78459. },
  78460. enumerable: true,
  78461. configurable: true
  78462. });
  78463. /**
  78464. * Disposes the renderer and frees up associated resources.
  78465. */
  78466. GeometryBufferRenderer.prototype.dispose = function () {
  78467. this.getGBuffer().dispose();
  78468. };
  78469. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78470. var _this = this;
  78471. var engine = this._scene.getEngine();
  78472. var count = this._enablePosition ? 3 : 2;
  78473. 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 });
  78474. if (!this.isSupported) {
  78475. return;
  78476. }
  78477. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78478. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78479. this._multiRenderTarget.refreshRate = 1;
  78480. this._multiRenderTarget.renderParticles = false;
  78481. this._multiRenderTarget.renderList = null;
  78482. // set default depth value to 1.0 (far away)
  78483. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78484. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78485. });
  78486. // Custom render function
  78487. var renderSubMesh = function (subMesh) {
  78488. var mesh = subMesh.getRenderingMesh();
  78489. var scene = _this._scene;
  78490. var engine = scene.getEngine();
  78491. var material = subMesh.getMaterial();
  78492. if (!material) {
  78493. return;
  78494. }
  78495. // Culling
  78496. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78497. // Managing instances
  78498. var batch = mesh._getInstancesRenderList(subMesh._id);
  78499. if (batch.mustReturn) {
  78500. return;
  78501. }
  78502. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78503. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78504. engine.enableEffect(_this._effect);
  78505. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78506. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78507. _this._effect.setMatrix("view", scene.getViewMatrix());
  78508. // Alpha test
  78509. if (material && material.needAlphaTesting()) {
  78510. var alphaTexture = material.getAlphaTestTexture();
  78511. if (alphaTexture) {
  78512. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78513. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78514. }
  78515. }
  78516. // Bones
  78517. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78518. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78519. }
  78520. // Draw
  78521. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78522. }
  78523. };
  78524. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78525. var index;
  78526. if (depthOnlySubMeshes.length) {
  78527. engine.setColorWrite(false);
  78528. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78529. renderSubMesh(depthOnlySubMeshes.data[index]);
  78530. }
  78531. engine.setColorWrite(true);
  78532. }
  78533. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78534. renderSubMesh(opaqueSubMeshes.data[index]);
  78535. }
  78536. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78537. renderSubMesh(alphaTestSubMeshes.data[index]);
  78538. }
  78539. };
  78540. };
  78541. return GeometryBufferRenderer;
  78542. }());
  78543. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78544. })(BABYLON || (BABYLON = {}));
  78545. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78546. var BABYLON;
  78547. (function (BABYLON) {
  78548. /**
  78549. * This groups together the common properties used for image processing either in direct forward pass
  78550. * or through post processing effect depending on the use of the image processing pipeline in your scene
  78551. * or not.
  78552. */
  78553. var ImageProcessingConfiguration = /** @class */ (function () {
  78554. function ImageProcessingConfiguration() {
  78555. /**
  78556. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  78557. */
  78558. this.colorCurves = new BABYLON.ColorCurves();
  78559. this._colorCurvesEnabled = false;
  78560. this._colorGradingEnabled = false;
  78561. this._colorGradingWithGreenDepth = true;
  78562. this._colorGradingBGR = true;
  78563. this._exposure = 1.0;
  78564. this._toneMappingEnabled = false;
  78565. this._contrast = 1.0;
  78566. /**
  78567. * Vignette stretch size.
  78568. */
  78569. this.vignetteStretch = 0;
  78570. /**
  78571. * Vignette centre X Offset.
  78572. */
  78573. this.vignetteCentreX = 0;
  78574. /**
  78575. * Vignette centre Y Offset.
  78576. */
  78577. this.vignetteCentreY = 0;
  78578. /**
  78579. * Vignette weight or intensity of the vignette effect.
  78580. */
  78581. this.vignetteWeight = 1.5;
  78582. /**
  78583. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78584. * if vignetteEnabled is set to true.
  78585. */
  78586. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  78587. /**
  78588. * Camera field of view used by the Vignette effect.
  78589. */
  78590. this.vignetteCameraFov = 0.5;
  78591. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  78592. this._vignetteEnabled = false;
  78593. this._applyByPostProcess = false;
  78594. this._isEnabled = true;
  78595. /**
  78596. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  78597. */
  78598. this.onUpdateParameters = new BABYLON.Observable();
  78599. }
  78600. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  78601. /**
  78602. * Gets wether the color curves effect is enabled.
  78603. */
  78604. get: function () {
  78605. return this._colorCurvesEnabled;
  78606. },
  78607. /**
  78608. * Sets wether the color curves effect is enabled.
  78609. */
  78610. set: function (value) {
  78611. if (this._colorCurvesEnabled === value) {
  78612. return;
  78613. }
  78614. this._colorCurvesEnabled = value;
  78615. this._updateParameters();
  78616. },
  78617. enumerable: true,
  78618. configurable: true
  78619. });
  78620. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  78621. /**
  78622. * Gets wether the color grading effect is enabled.
  78623. */
  78624. get: function () {
  78625. return this._colorGradingEnabled;
  78626. },
  78627. /**
  78628. * Sets wether the color grading effect is enabled.
  78629. */
  78630. set: function (value) {
  78631. if (this._colorGradingEnabled === value) {
  78632. return;
  78633. }
  78634. this._colorGradingEnabled = value;
  78635. this._updateParameters();
  78636. },
  78637. enumerable: true,
  78638. configurable: true
  78639. });
  78640. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  78641. /**
  78642. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  78643. */
  78644. get: function () {
  78645. return this._colorGradingWithGreenDepth;
  78646. },
  78647. /**
  78648. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  78649. */
  78650. set: function (value) {
  78651. if (this._colorGradingWithGreenDepth === value) {
  78652. return;
  78653. }
  78654. this._colorGradingWithGreenDepth = value;
  78655. this._updateParameters();
  78656. },
  78657. enumerable: true,
  78658. configurable: true
  78659. });
  78660. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  78661. /**
  78662. * Gets wether the color grading texture contains BGR values.
  78663. */
  78664. get: function () {
  78665. return this._colorGradingBGR;
  78666. },
  78667. /**
  78668. * Sets wether the color grading texture contains BGR values.
  78669. */
  78670. set: function (value) {
  78671. if (this._colorGradingBGR === value) {
  78672. return;
  78673. }
  78674. this._colorGradingBGR = value;
  78675. this._updateParameters();
  78676. },
  78677. enumerable: true,
  78678. configurable: true
  78679. });
  78680. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  78681. /**
  78682. * Gets the Exposure used in the effect.
  78683. */
  78684. get: function () {
  78685. return this._exposure;
  78686. },
  78687. /**
  78688. * Sets the Exposure used in the effect.
  78689. */
  78690. set: function (value) {
  78691. if (this._exposure === value) {
  78692. return;
  78693. }
  78694. this._exposure = value;
  78695. this._updateParameters();
  78696. },
  78697. enumerable: true,
  78698. configurable: true
  78699. });
  78700. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  78701. /**
  78702. * Gets wether the tone mapping effect is enabled.
  78703. */
  78704. get: function () {
  78705. return this._toneMappingEnabled;
  78706. },
  78707. /**
  78708. * Sets wether the tone mapping effect is enabled.
  78709. */
  78710. set: function (value) {
  78711. if (this._toneMappingEnabled === value) {
  78712. return;
  78713. }
  78714. this._toneMappingEnabled = value;
  78715. this._updateParameters();
  78716. },
  78717. enumerable: true,
  78718. configurable: true
  78719. });
  78720. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  78721. /**
  78722. * Gets the contrast used in the effect.
  78723. */
  78724. get: function () {
  78725. return this._contrast;
  78726. },
  78727. /**
  78728. * Sets the contrast used in the effect.
  78729. */
  78730. set: function (value) {
  78731. if (this._contrast === value) {
  78732. return;
  78733. }
  78734. this._contrast = value;
  78735. this._updateParameters();
  78736. },
  78737. enumerable: true,
  78738. configurable: true
  78739. });
  78740. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  78741. /**
  78742. * Gets the vignette blend mode allowing different kind of effect.
  78743. */
  78744. get: function () {
  78745. return this._vignetteBlendMode;
  78746. },
  78747. /**
  78748. * Sets the vignette blend mode allowing different kind of effect.
  78749. */
  78750. set: function (value) {
  78751. if (this._vignetteBlendMode === value) {
  78752. return;
  78753. }
  78754. this._vignetteBlendMode = value;
  78755. this._updateParameters();
  78756. },
  78757. enumerable: true,
  78758. configurable: true
  78759. });
  78760. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  78761. /**
  78762. * Gets wether the vignette effect is enabled.
  78763. */
  78764. get: function () {
  78765. return this._vignetteEnabled;
  78766. },
  78767. /**
  78768. * Sets wether the vignette effect is enabled.
  78769. */
  78770. set: function (value) {
  78771. if (this._vignetteEnabled === value) {
  78772. return;
  78773. }
  78774. this._vignetteEnabled = value;
  78775. this._updateParameters();
  78776. },
  78777. enumerable: true,
  78778. configurable: true
  78779. });
  78780. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  78781. /**
  78782. * Gets wether the image processing is applied through a post process or not.
  78783. */
  78784. get: function () {
  78785. return this._applyByPostProcess;
  78786. },
  78787. /**
  78788. * Sets wether the image processing is applied through a post process or not.
  78789. */
  78790. set: function (value) {
  78791. if (this._applyByPostProcess === value) {
  78792. return;
  78793. }
  78794. this._applyByPostProcess = value;
  78795. this._updateParameters();
  78796. },
  78797. enumerable: true,
  78798. configurable: true
  78799. });
  78800. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  78801. /**
  78802. * Gets wether the image processing is enabled or not.
  78803. */
  78804. get: function () {
  78805. return this._isEnabled;
  78806. },
  78807. /**
  78808. * Sets wether the image processing is enabled or not.
  78809. */
  78810. set: function (value) {
  78811. if (this._isEnabled === value) {
  78812. return;
  78813. }
  78814. this._isEnabled = value;
  78815. this._updateParameters();
  78816. },
  78817. enumerable: true,
  78818. configurable: true
  78819. });
  78820. /**
  78821. * Method called each time the image processing information changes requires to recompile the effect.
  78822. */
  78823. ImageProcessingConfiguration.prototype._updateParameters = function () {
  78824. this.onUpdateParameters.notifyObservers(this);
  78825. };
  78826. ImageProcessingConfiguration.prototype.getClassName = function () {
  78827. return "ImageProcessingConfiguration";
  78828. };
  78829. /**
  78830. * Prepare the list of uniforms associated with the Image Processing effects.
  78831. * @param uniformsList The list of uniforms used in the effect
  78832. * @param defines the list of defines currently in use
  78833. */
  78834. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  78835. if (defines.EXPOSURE) {
  78836. uniforms.push("exposureLinear");
  78837. }
  78838. if (defines.CONTRAST) {
  78839. uniforms.push("contrast");
  78840. }
  78841. if (defines.COLORGRADING) {
  78842. uniforms.push("colorTransformSettings");
  78843. }
  78844. if (defines.VIGNETTE) {
  78845. uniforms.push("vInverseScreenSize");
  78846. uniforms.push("vignetteSettings1");
  78847. uniforms.push("vignetteSettings2");
  78848. }
  78849. if (defines.COLORCURVES) {
  78850. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  78851. }
  78852. };
  78853. /**
  78854. * Prepare the list of samplers associated with the Image Processing effects.
  78855. * @param uniformsList The list of uniforms used in the effect
  78856. * @param defines the list of defines currently in use
  78857. */
  78858. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  78859. if (defines.COLORGRADING) {
  78860. samplersList.push("txColorTransform");
  78861. }
  78862. };
  78863. /**
  78864. * Prepare the list of defines associated to the shader.
  78865. * @param defines the list of defines to complete
  78866. */
  78867. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  78868. if (forPostProcess === void 0) { forPostProcess = false; }
  78869. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  78870. defines.VIGNETTE = false;
  78871. defines.TONEMAPPING = false;
  78872. defines.CONTRAST = false;
  78873. defines.EXPOSURE = false;
  78874. defines.COLORCURVES = false;
  78875. defines.COLORGRADING = false;
  78876. defines.COLORGRADING3D = false;
  78877. defines.IMAGEPROCESSING = false;
  78878. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  78879. return;
  78880. }
  78881. defines.VIGNETTE = this.vignetteEnabled;
  78882. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  78883. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  78884. defines.TONEMAPPING = this.toneMappingEnabled;
  78885. defines.CONTRAST = (this.contrast !== 1.0);
  78886. defines.EXPOSURE = (this.exposure !== 1.0);
  78887. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  78888. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  78889. if (defines.COLORGRADING) {
  78890. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  78891. }
  78892. else {
  78893. defines.COLORGRADING3D = false;
  78894. }
  78895. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  78896. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  78897. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  78898. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  78899. };
  78900. /**
  78901. * Returns true if all the image processing information are ready.
  78902. */
  78903. ImageProcessingConfiguration.prototype.isReady = function () {
  78904. // Color Grading texure can not be none blocking.
  78905. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  78906. };
  78907. /**
  78908. * Binds the image processing to the shader.
  78909. * @param effect The effect to bind to
  78910. */
  78911. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  78912. if (aspectRatio === void 0) { aspectRatio = 1; }
  78913. // Color Curves
  78914. if (this._colorCurvesEnabled && this.colorCurves) {
  78915. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  78916. }
  78917. // Vignette
  78918. if (this._vignetteEnabled) {
  78919. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  78920. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  78921. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  78922. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  78923. var vignetteScaleX = vignetteScaleY * aspectRatio;
  78924. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  78925. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  78926. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  78927. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  78928. var vignettePower = -2.0 * this.vignetteWeight;
  78929. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  78930. }
  78931. // Exposure
  78932. effect.setFloat("exposureLinear", this.exposure);
  78933. // Contrast
  78934. effect.setFloat("contrast", this.contrast);
  78935. // Color transform settings
  78936. if (this.colorGradingTexture) {
  78937. effect.setTexture("txColorTransform", this.colorGradingTexture);
  78938. var textureSize = this.colorGradingTexture.getSize().height;
  78939. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  78940. 0.5 / textureSize, // textureOffset
  78941. textureSize, // textureSize
  78942. this.colorGradingTexture.level // weight
  78943. );
  78944. }
  78945. };
  78946. /**
  78947. * Clones the current image processing instance.
  78948. * @return The cloned image processing
  78949. */
  78950. ImageProcessingConfiguration.prototype.clone = function () {
  78951. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  78952. };
  78953. /**
  78954. * Serializes the current image processing instance to a json representation.
  78955. * @return a JSON representation
  78956. */
  78957. ImageProcessingConfiguration.prototype.serialize = function () {
  78958. return BABYLON.SerializationHelper.Serialize(this);
  78959. };
  78960. /**
  78961. * Parses the image processing from a json representation.
  78962. * @param source the JSON source to parse
  78963. * @return The parsed image processing
  78964. */
  78965. ImageProcessingConfiguration.Parse = function (source) {
  78966. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  78967. };
  78968. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  78969. /**
  78970. * Used to apply the vignette as a mix with the pixel color.
  78971. */
  78972. get: function () {
  78973. return this._VIGNETTEMODE_MULTIPLY;
  78974. },
  78975. enumerable: true,
  78976. configurable: true
  78977. });
  78978. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  78979. /**
  78980. * Used to apply the vignette as a replacement of the pixel color.
  78981. */
  78982. get: function () {
  78983. return this._VIGNETTEMODE_OPAQUE;
  78984. },
  78985. enumerable: true,
  78986. configurable: true
  78987. });
  78988. // Static constants associated to the image processing.
  78989. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  78990. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  78991. __decorate([
  78992. BABYLON.serializeAsColorCurves()
  78993. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  78994. __decorate([
  78995. BABYLON.serialize()
  78996. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  78997. __decorate([
  78998. BABYLON.serializeAsTexture()
  78999. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  79000. __decorate([
  79001. BABYLON.serialize()
  79002. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  79003. __decorate([
  79004. BABYLON.serialize()
  79005. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  79006. __decorate([
  79007. BABYLON.serialize()
  79008. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  79009. __decorate([
  79010. BABYLON.serialize()
  79011. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  79012. __decorate([
  79013. BABYLON.serialize()
  79014. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  79015. __decorate([
  79016. BABYLON.serialize()
  79017. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  79018. __decorate([
  79019. BABYLON.serialize()
  79020. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  79021. __decorate([
  79022. BABYLON.serialize()
  79023. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  79024. __decorate([
  79025. BABYLON.serialize()
  79026. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  79027. __decorate([
  79028. BABYLON.serialize()
  79029. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  79030. __decorate([
  79031. BABYLON.serializeAsColor4()
  79032. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  79033. __decorate([
  79034. BABYLON.serialize()
  79035. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  79036. __decorate([
  79037. BABYLON.serialize()
  79038. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  79039. __decorate([
  79040. BABYLON.serialize()
  79041. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  79042. __decorate([
  79043. BABYLON.serialize()
  79044. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  79045. __decorate([
  79046. BABYLON.serialize()
  79047. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  79048. return ImageProcessingConfiguration;
  79049. }());
  79050. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  79051. })(BABYLON || (BABYLON = {}));
  79052. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  79053. var BABYLON;
  79054. (function (BABYLON) {
  79055. /**
  79056. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  79057. * It can help converting any input color in a desired output one. This can then be used to create effects
  79058. * from sepia, black and white to sixties or futuristic rendering...
  79059. *
  79060. * The only supported format is currently 3dl.
  79061. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  79062. */
  79063. var ColorGradingTexture = /** @class */ (function (_super) {
  79064. __extends(ColorGradingTexture, _super);
  79065. /**
  79066. * Instantiates a ColorGradingTexture from the following parameters.
  79067. *
  79068. * @param url The location of the color gradind data (currently only supporting 3dl)
  79069. * @param scene The scene the texture will be used in
  79070. */
  79071. function ColorGradingTexture(url, scene) {
  79072. var _this = _super.call(this, scene) || this;
  79073. if (!url) {
  79074. return _this;
  79075. }
  79076. _this._engine = scene.getEngine();
  79077. _this._textureMatrix = BABYLON.Matrix.Identity();
  79078. _this.name = url;
  79079. _this.url = url;
  79080. _this.hasAlpha = false;
  79081. _this.isCube = false;
  79082. _this.is3D = _this._engine.webGLVersion > 1;
  79083. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79084. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79085. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79086. _this.anisotropicFilteringLevel = 1;
  79087. _this._texture = _this._getFromCache(url, true);
  79088. if (!_this._texture) {
  79089. if (!scene.useDelayedTextureLoading) {
  79090. _this.loadTexture();
  79091. }
  79092. else {
  79093. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  79094. }
  79095. }
  79096. return _this;
  79097. }
  79098. /**
  79099. * Returns the texture matrix used in most of the material.
  79100. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  79101. */
  79102. ColorGradingTexture.prototype.getTextureMatrix = function () {
  79103. return this._textureMatrix;
  79104. };
  79105. /**
  79106. * Occurs when the file being loaded is a .3dl LUT file.
  79107. */
  79108. ColorGradingTexture.prototype.load3dlTexture = function () {
  79109. var engine = this._engine;
  79110. var texture;
  79111. if (engine.webGLVersion === 1) {
  79112. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79113. }
  79114. else {
  79115. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79116. }
  79117. this._texture = texture;
  79118. var callback = function (text) {
  79119. if (typeof text !== "string") {
  79120. return;
  79121. }
  79122. var data = null;
  79123. var tempData = null;
  79124. var line;
  79125. var lines = text.split('\n');
  79126. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  79127. var maxColor = 0;
  79128. for (var i = 0; i < lines.length; i++) {
  79129. line = lines[i];
  79130. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  79131. continue;
  79132. if (line.indexOf('#') === 0)
  79133. continue;
  79134. var words = line.split(" ");
  79135. if (size === 0) {
  79136. // Number of space + one
  79137. size = words.length;
  79138. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  79139. tempData = new Float32Array(size * size * size * 4);
  79140. continue;
  79141. }
  79142. if (size != 0) {
  79143. var r = Math.max(parseInt(words[0]), 0);
  79144. var g = Math.max(parseInt(words[1]), 0);
  79145. var b = Math.max(parseInt(words[2]), 0);
  79146. maxColor = Math.max(r, maxColor);
  79147. maxColor = Math.max(g, maxColor);
  79148. maxColor = Math.max(b, maxColor);
  79149. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  79150. if (tempData) {
  79151. tempData[pixelStorageIndex + 0] = r;
  79152. tempData[pixelStorageIndex + 1] = g;
  79153. tempData[pixelStorageIndex + 2] = b;
  79154. }
  79155. pixelIndexSlice++;
  79156. if (pixelIndexSlice % size == 0) {
  79157. pixelIndexH++;
  79158. pixelIndexSlice = 0;
  79159. if (pixelIndexH % size == 0) {
  79160. pixelIndexW++;
  79161. pixelIndexH = 0;
  79162. }
  79163. }
  79164. }
  79165. }
  79166. if (tempData && data) {
  79167. for (var i = 0; i < tempData.length; i++) {
  79168. if (i > 0 && (i + 1) % 4 === 0) {
  79169. data[i] = 255;
  79170. }
  79171. else {
  79172. var value = tempData[i];
  79173. data[i] = (value / maxColor * 255);
  79174. }
  79175. }
  79176. }
  79177. if (texture.is3D) {
  79178. texture.updateSize(size, size, size);
  79179. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79180. }
  79181. else {
  79182. texture.updateSize(size * size, size);
  79183. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79184. }
  79185. };
  79186. var scene = this.getScene();
  79187. if (scene) {
  79188. scene._loadFile(this.url, callback);
  79189. }
  79190. else {
  79191. this._engine._loadFile(this.url, callback);
  79192. }
  79193. return this._texture;
  79194. };
  79195. /**
  79196. * Starts the loading process of the texture.
  79197. */
  79198. ColorGradingTexture.prototype.loadTexture = function () {
  79199. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  79200. this.load3dlTexture();
  79201. }
  79202. };
  79203. /**
  79204. * Clones the color gradind texture.
  79205. */
  79206. ColorGradingTexture.prototype.clone = function () {
  79207. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  79208. // Base texture
  79209. newTexture.level = this.level;
  79210. return newTexture;
  79211. };
  79212. /**
  79213. * Called during delayed load for textures.
  79214. */
  79215. ColorGradingTexture.prototype.delayLoad = function () {
  79216. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79217. return;
  79218. }
  79219. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79220. this._texture = this._getFromCache(this.url, true);
  79221. if (!this._texture) {
  79222. this.loadTexture();
  79223. }
  79224. };
  79225. /**
  79226. * Parses a color grading texture serialized by Babylon.
  79227. * @param parsedTexture The texture information being parsedTexture
  79228. * @param scene The scene to load the texture in
  79229. * @param rootUrl The root url of the data assets to load
  79230. * @return A color gradind texture
  79231. */
  79232. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79233. var texture = null;
  79234. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79235. texture = new ColorGradingTexture(parsedTexture.name, scene);
  79236. texture.name = parsedTexture.name;
  79237. texture.level = parsedTexture.level;
  79238. }
  79239. return texture;
  79240. };
  79241. /**
  79242. * Serializes the LUT texture to json format.
  79243. */
  79244. ColorGradingTexture.prototype.serialize = function () {
  79245. if (!this.name) {
  79246. return null;
  79247. }
  79248. var serializationObject = {};
  79249. serializationObject.name = this.name;
  79250. serializationObject.level = this.level;
  79251. serializationObject.customType = "BABYLON.ColorGradingTexture";
  79252. return serializationObject;
  79253. };
  79254. /**
  79255. * Empty line regex stored for GC.
  79256. */
  79257. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  79258. return ColorGradingTexture;
  79259. }(BABYLON.BaseTexture));
  79260. BABYLON.ColorGradingTexture = ColorGradingTexture;
  79261. })(BABYLON || (BABYLON = {}));
  79262. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  79263. var BABYLON;
  79264. (function (BABYLON) {
  79265. /**
  79266. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79267. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79268. * 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;
  79269. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79270. */
  79271. var ColorCurves = /** @class */ (function () {
  79272. function ColorCurves() {
  79273. this._dirty = true;
  79274. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  79275. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  79276. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79277. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  79278. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79279. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  79280. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  79281. this._globalHue = 30;
  79282. this._globalDensity = 0;
  79283. this._globalSaturation = 0;
  79284. this._globalExposure = 0;
  79285. this._highlightsHue = 30;
  79286. this._highlightsDensity = 0;
  79287. this._highlightsSaturation = 0;
  79288. this._highlightsExposure = 0;
  79289. this._midtonesHue = 30;
  79290. this._midtonesDensity = 0;
  79291. this._midtonesSaturation = 0;
  79292. this._midtonesExposure = 0;
  79293. this._shadowsHue = 30;
  79294. this._shadowsDensity = 0;
  79295. this._shadowsSaturation = 0;
  79296. this._shadowsExposure = 0;
  79297. }
  79298. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  79299. /**
  79300. * Gets the global Hue value.
  79301. * 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).
  79302. */
  79303. get: function () {
  79304. return this._globalHue;
  79305. },
  79306. /**
  79307. * Sets the global Hue value.
  79308. * 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).
  79309. */
  79310. set: function (value) {
  79311. this._globalHue = value;
  79312. this._dirty = true;
  79313. },
  79314. enumerable: true,
  79315. configurable: true
  79316. });
  79317. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  79318. /**
  79319. * Gets the global Density value.
  79320. * 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.
  79321. * Values less than zero provide a filter of opposite hue.
  79322. */
  79323. get: function () {
  79324. return this._globalDensity;
  79325. },
  79326. /**
  79327. * Sets the global Density value.
  79328. * 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.
  79329. * Values less than zero provide a filter of opposite hue.
  79330. */
  79331. set: function (value) {
  79332. this._globalDensity = value;
  79333. this._dirty = true;
  79334. },
  79335. enumerable: true,
  79336. configurable: true
  79337. });
  79338. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  79339. /**
  79340. * Gets the global Saturation value.
  79341. * 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.
  79342. */
  79343. get: function () {
  79344. return this._globalSaturation;
  79345. },
  79346. /**
  79347. * Sets the global Saturation value.
  79348. * 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.
  79349. */
  79350. set: function (value) {
  79351. this._globalSaturation = value;
  79352. this._dirty = true;
  79353. },
  79354. enumerable: true,
  79355. configurable: true
  79356. });
  79357. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  79358. /**
  79359. * Gets the global Exposure value.
  79360. * 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.
  79361. */
  79362. get: function () {
  79363. return this._globalExposure;
  79364. },
  79365. /**
  79366. * Sets the global Exposure value.
  79367. * 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.
  79368. */
  79369. set: function (value) {
  79370. this._globalExposure = value;
  79371. this._dirty = true;
  79372. },
  79373. enumerable: true,
  79374. configurable: true
  79375. });
  79376. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  79377. /**
  79378. * Gets the highlights Hue value.
  79379. * 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).
  79380. */
  79381. get: function () {
  79382. return this._highlightsHue;
  79383. },
  79384. /**
  79385. * Sets the highlights Hue value.
  79386. * 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).
  79387. */
  79388. set: function (value) {
  79389. this._highlightsHue = value;
  79390. this._dirty = true;
  79391. },
  79392. enumerable: true,
  79393. configurable: true
  79394. });
  79395. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  79396. /**
  79397. * Gets the highlights Density value.
  79398. * 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.
  79399. * Values less than zero provide a filter of opposite hue.
  79400. */
  79401. get: function () {
  79402. return this._highlightsDensity;
  79403. },
  79404. /**
  79405. * Sets the highlights Density value.
  79406. * 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.
  79407. * Values less than zero provide a filter of opposite hue.
  79408. */
  79409. set: function (value) {
  79410. this._highlightsDensity = value;
  79411. this._dirty = true;
  79412. },
  79413. enumerable: true,
  79414. configurable: true
  79415. });
  79416. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  79417. /**
  79418. * Gets the highlights Saturation value.
  79419. * 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.
  79420. */
  79421. get: function () {
  79422. return this._highlightsSaturation;
  79423. },
  79424. /**
  79425. * Sets the highlights Saturation value.
  79426. * 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.
  79427. */
  79428. set: function (value) {
  79429. this._highlightsSaturation = value;
  79430. this._dirty = true;
  79431. },
  79432. enumerable: true,
  79433. configurable: true
  79434. });
  79435. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  79436. /**
  79437. * Gets the highlights Exposure value.
  79438. * 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.
  79439. */
  79440. get: function () {
  79441. return this._highlightsExposure;
  79442. },
  79443. /**
  79444. * Sets the highlights Exposure value.
  79445. * 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.
  79446. */
  79447. set: function (value) {
  79448. this._highlightsExposure = value;
  79449. this._dirty = true;
  79450. },
  79451. enumerable: true,
  79452. configurable: true
  79453. });
  79454. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  79455. /**
  79456. * Gets the midtones Hue value.
  79457. * 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).
  79458. */
  79459. get: function () {
  79460. return this._midtonesHue;
  79461. },
  79462. /**
  79463. * Sets the midtones Hue value.
  79464. * 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).
  79465. */
  79466. set: function (value) {
  79467. this._midtonesHue = value;
  79468. this._dirty = true;
  79469. },
  79470. enumerable: true,
  79471. configurable: true
  79472. });
  79473. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  79474. /**
  79475. * Gets the midtones Density value.
  79476. * 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.
  79477. * Values less than zero provide a filter of opposite hue.
  79478. */
  79479. get: function () {
  79480. return this._midtonesDensity;
  79481. },
  79482. /**
  79483. * Sets the midtones Density value.
  79484. * 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.
  79485. * Values less than zero provide a filter of opposite hue.
  79486. */
  79487. set: function (value) {
  79488. this._midtonesDensity = value;
  79489. this._dirty = true;
  79490. },
  79491. enumerable: true,
  79492. configurable: true
  79493. });
  79494. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  79495. /**
  79496. * Gets the midtones Saturation value.
  79497. * 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.
  79498. */
  79499. get: function () {
  79500. return this._midtonesSaturation;
  79501. },
  79502. /**
  79503. * Sets the midtones Saturation value.
  79504. * 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.
  79505. */
  79506. set: function (value) {
  79507. this._midtonesSaturation = value;
  79508. this._dirty = true;
  79509. },
  79510. enumerable: true,
  79511. configurable: true
  79512. });
  79513. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  79514. /**
  79515. * Gets the midtones Exposure value.
  79516. * 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.
  79517. */
  79518. get: function () {
  79519. return this._midtonesExposure;
  79520. },
  79521. /**
  79522. * Sets the midtones Exposure value.
  79523. * 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.
  79524. */
  79525. set: function (value) {
  79526. this._midtonesExposure = value;
  79527. this._dirty = true;
  79528. },
  79529. enumerable: true,
  79530. configurable: true
  79531. });
  79532. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  79533. /**
  79534. * Gets the shadows Hue value.
  79535. * 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).
  79536. */
  79537. get: function () {
  79538. return this._shadowsHue;
  79539. },
  79540. /**
  79541. * Sets the shadows Hue value.
  79542. * 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).
  79543. */
  79544. set: function (value) {
  79545. this._shadowsHue = value;
  79546. this._dirty = true;
  79547. },
  79548. enumerable: true,
  79549. configurable: true
  79550. });
  79551. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  79552. /**
  79553. * Gets the shadows Density value.
  79554. * 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.
  79555. * Values less than zero provide a filter of opposite hue.
  79556. */
  79557. get: function () {
  79558. return this._shadowsDensity;
  79559. },
  79560. /**
  79561. * Sets the shadows Density value.
  79562. * 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.
  79563. * Values less than zero provide a filter of opposite hue.
  79564. */
  79565. set: function (value) {
  79566. this._shadowsDensity = value;
  79567. this._dirty = true;
  79568. },
  79569. enumerable: true,
  79570. configurable: true
  79571. });
  79572. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  79573. /**
  79574. * Gets the shadows Saturation value.
  79575. * 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.
  79576. */
  79577. get: function () {
  79578. return this._shadowsSaturation;
  79579. },
  79580. /**
  79581. * Sets the shadows Saturation value.
  79582. * 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.
  79583. */
  79584. set: function (value) {
  79585. this._shadowsSaturation = value;
  79586. this._dirty = true;
  79587. },
  79588. enumerable: true,
  79589. configurable: true
  79590. });
  79591. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  79592. /**
  79593. * Gets the shadows Exposure value.
  79594. * 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.
  79595. */
  79596. get: function () {
  79597. return this._shadowsExposure;
  79598. },
  79599. /**
  79600. * Sets the shadows Exposure value.
  79601. * 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.
  79602. */
  79603. set: function (value) {
  79604. this._shadowsExposure = value;
  79605. this._dirty = true;
  79606. },
  79607. enumerable: true,
  79608. configurable: true
  79609. });
  79610. ColorCurves.prototype.getClassName = function () {
  79611. return "ColorCurves";
  79612. };
  79613. /**
  79614. * Binds the color curves to the shader.
  79615. * @param colorCurves The color curve to bind
  79616. * @param effect The effect to bind to
  79617. */
  79618. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  79619. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  79620. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  79621. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  79622. if (colorCurves._dirty) {
  79623. colorCurves._dirty = false;
  79624. // Fill in global info.
  79625. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  79626. // Compute highlights info.
  79627. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  79628. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  79629. // Compute midtones info.
  79630. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  79631. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  79632. // Compute shadows info.
  79633. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  79634. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  79635. // Compute deltas (neutral is midtones).
  79636. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  79637. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  79638. }
  79639. if (effect) {
  79640. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  79641. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  79642. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  79643. }
  79644. };
  79645. /**
  79646. * Prepare the list of uniforms associated with the ColorCurves effects.
  79647. * @param uniformsList The list of uniforms used in the effect
  79648. */
  79649. ColorCurves.PrepareUniforms = function (uniformsList) {
  79650. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  79651. };
  79652. /**
  79653. * Returns color grading data based on a hue, density, saturation and exposure value.
  79654. * @param filterHue The hue of the color filter.
  79655. * @param filterDensity The density of the color filter.
  79656. * @param saturation The saturation.
  79657. * @param exposure The exposure.
  79658. * @param result The result data container.
  79659. */
  79660. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  79661. if (hue == null) {
  79662. return;
  79663. }
  79664. hue = ColorCurves.clamp(hue, 0, 360);
  79665. density = ColorCurves.clamp(density, -100, 100);
  79666. saturation = ColorCurves.clamp(saturation, -100, 100);
  79667. exposure = ColorCurves.clamp(exposure, -100, 100);
  79668. // Remap the slider/config filter density with non-linear mapping and also scale by half
  79669. // so that the maximum filter density is only 50% control. This provides fine control
  79670. // for small values and reasonable range.
  79671. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  79672. density *= 0.5;
  79673. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  79674. if (density < 0) {
  79675. density *= -1;
  79676. hue = (hue + 180) % 360;
  79677. }
  79678. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  79679. result.scaleToRef(2, result);
  79680. result.a = 1 + 0.01 * saturation;
  79681. };
  79682. /**
  79683. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  79684. * @param value The input slider value in range [-100,100].
  79685. * @returns Adjusted value.
  79686. */
  79687. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  79688. value /= 100;
  79689. var x = Math.abs(value);
  79690. x = Math.pow(x, 2);
  79691. if (value < 0) {
  79692. x *= -1;
  79693. }
  79694. x *= 100;
  79695. return x;
  79696. };
  79697. /**
  79698. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  79699. * @param hue The hue (H) input.
  79700. * @param saturation The saturation (S) input.
  79701. * @param brightness The brightness (B) input.
  79702. * @result An RGBA color represented as Vector4.
  79703. */
  79704. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  79705. var h = ColorCurves.clamp(hue, 0, 360);
  79706. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  79707. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  79708. if (s === 0) {
  79709. result.r = v;
  79710. result.g = v;
  79711. result.b = v;
  79712. }
  79713. else {
  79714. // sector 0 to 5
  79715. h /= 60;
  79716. var i = Math.floor(h);
  79717. // fractional part of h
  79718. var f = h - i;
  79719. var p = v * (1 - s);
  79720. var q = v * (1 - s * f);
  79721. var t = v * (1 - s * (1 - f));
  79722. switch (i) {
  79723. case 0:
  79724. result.r = v;
  79725. result.g = t;
  79726. result.b = p;
  79727. break;
  79728. case 1:
  79729. result.r = q;
  79730. result.g = v;
  79731. result.b = p;
  79732. break;
  79733. case 2:
  79734. result.r = p;
  79735. result.g = v;
  79736. result.b = t;
  79737. break;
  79738. case 3:
  79739. result.r = p;
  79740. result.g = q;
  79741. result.b = v;
  79742. break;
  79743. case 4:
  79744. result.r = t;
  79745. result.g = p;
  79746. result.b = v;
  79747. break;
  79748. default: // case 5:
  79749. result.r = v;
  79750. result.g = p;
  79751. result.b = q;
  79752. break;
  79753. }
  79754. }
  79755. result.a = 1;
  79756. };
  79757. /**
  79758. * Returns a value clamped between min and max
  79759. * @param value The value to clamp
  79760. * @param min The minimum of value
  79761. * @param max The maximum of value
  79762. * @returns The clamped value.
  79763. */
  79764. ColorCurves.clamp = function (value, min, max) {
  79765. return Math.min(Math.max(value, min), max);
  79766. };
  79767. /**
  79768. * Clones the current color curve instance.
  79769. * @return The cloned curves
  79770. */
  79771. ColorCurves.prototype.clone = function () {
  79772. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  79773. };
  79774. /**
  79775. * Serializes the current color curve instance to a json representation.
  79776. * @return a JSON representation
  79777. */
  79778. ColorCurves.prototype.serialize = function () {
  79779. return BABYLON.SerializationHelper.Serialize(this);
  79780. };
  79781. /**
  79782. * Parses the color curve from a json representation.
  79783. * @param source the JSON source to parse
  79784. * @return The parsed curves
  79785. */
  79786. ColorCurves.Parse = function (source) {
  79787. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  79788. };
  79789. __decorate([
  79790. BABYLON.serialize()
  79791. ], ColorCurves.prototype, "_globalHue", void 0);
  79792. __decorate([
  79793. BABYLON.serialize()
  79794. ], ColorCurves.prototype, "_globalDensity", void 0);
  79795. __decorate([
  79796. BABYLON.serialize()
  79797. ], ColorCurves.prototype, "_globalSaturation", void 0);
  79798. __decorate([
  79799. BABYLON.serialize()
  79800. ], ColorCurves.prototype, "_globalExposure", void 0);
  79801. __decorate([
  79802. BABYLON.serialize()
  79803. ], ColorCurves.prototype, "_highlightsHue", void 0);
  79804. __decorate([
  79805. BABYLON.serialize()
  79806. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  79807. __decorate([
  79808. BABYLON.serialize()
  79809. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  79810. __decorate([
  79811. BABYLON.serialize()
  79812. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  79813. __decorate([
  79814. BABYLON.serialize()
  79815. ], ColorCurves.prototype, "_midtonesHue", void 0);
  79816. __decorate([
  79817. BABYLON.serialize()
  79818. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  79819. __decorate([
  79820. BABYLON.serialize()
  79821. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  79822. __decorate([
  79823. BABYLON.serialize()
  79824. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  79825. return ColorCurves;
  79826. }());
  79827. BABYLON.ColorCurves = ColorCurves;
  79828. })(BABYLON || (BABYLON = {}));
  79829. //# sourceMappingURL=babylon.colorCurves.js.map
  79830. var BABYLON;
  79831. (function (BABYLON) {
  79832. var RefractionPostProcess = /** @class */ (function (_super) {
  79833. __extends(RefractionPostProcess, _super);
  79834. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  79835. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  79836. _this.color = color;
  79837. _this.depth = depth;
  79838. _this.colorLevel = colorLevel;
  79839. _this._ownRefractionTexture = true;
  79840. _this.onActivateObservable.add(function (cam) {
  79841. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  79842. });
  79843. _this.onApplyObservable.add(function (effect) {
  79844. effect.setColor3("baseColor", _this.color);
  79845. effect.setFloat("depth", _this.depth);
  79846. effect.setFloat("colorLevel", _this.colorLevel);
  79847. effect.setTexture("refractionSampler", _this._refTexture);
  79848. });
  79849. return _this;
  79850. }
  79851. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  79852. /**
  79853. * Gets or sets the refraction texture
  79854. * Please note that you are responsible for disposing the texture if you set it manually
  79855. */
  79856. get: function () {
  79857. return this._refTexture;
  79858. },
  79859. set: function (value) {
  79860. if (this._refTexture && this._ownRefractionTexture) {
  79861. this._refTexture.dispose();
  79862. }
  79863. this._refTexture = value;
  79864. this._ownRefractionTexture = false;
  79865. },
  79866. enumerable: true,
  79867. configurable: true
  79868. });
  79869. // Methods
  79870. RefractionPostProcess.prototype.dispose = function (camera) {
  79871. if (this._refTexture && this._ownRefractionTexture) {
  79872. this._refTexture.dispose();
  79873. this._refTexture = null;
  79874. }
  79875. _super.prototype.dispose.call(this, camera);
  79876. };
  79877. return RefractionPostProcess;
  79878. }(BABYLON.PostProcess));
  79879. BABYLON.RefractionPostProcess = RefractionPostProcess;
  79880. })(BABYLON || (BABYLON = {}));
  79881. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  79882. var BABYLON;
  79883. (function (BABYLON) {
  79884. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  79885. __extends(BlackAndWhitePostProcess, _super);
  79886. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  79887. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  79888. _this.degree = 1;
  79889. _this.onApplyObservable.add(function (effect) {
  79890. effect.setFloat("degree", _this.degree);
  79891. });
  79892. return _this;
  79893. }
  79894. return BlackAndWhitePostProcess;
  79895. }(BABYLON.PostProcess));
  79896. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  79897. })(BABYLON || (BABYLON = {}));
  79898. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  79899. var BABYLON;
  79900. (function (BABYLON) {
  79901. /**
  79902. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  79903. * input texture to perform effects such as edge detection or sharpening
  79904. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  79905. */
  79906. var ConvolutionPostProcess = /** @class */ (function (_super) {
  79907. __extends(ConvolutionPostProcess, _super);
  79908. /**
  79909. * Creates a new instance ConvolutionPostProcess
  79910. * @param name The name of the effect.
  79911. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  79912. * @param options The required width/height ratio to downsize to before computing the render pass.
  79913. * @param camera The camera to apply the render pass to.
  79914. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79915. * @param engine The engine which the post process will be applied. (default: current engine)
  79916. * @param reusable If the post process can be reused on the same frame. (default: false)
  79917. * @param textureType Type of textures used when performing the post process. (default: 0)
  79918. */
  79919. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  79920. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79921. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79922. _this.kernel = kernel;
  79923. _this.onApply = function (effect) {
  79924. effect.setFloat2("screenSize", _this.width, _this.height);
  79925. effect.setArray("kernel", _this.kernel);
  79926. };
  79927. return _this;
  79928. }
  79929. // Statics
  79930. /**
  79931. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79932. */
  79933. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  79934. /**
  79935. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79936. */
  79937. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  79938. /**
  79939. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79940. */
  79941. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  79942. /**
  79943. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79944. */
  79945. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  79946. /**
  79947. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79948. */
  79949. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  79950. /**
  79951. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79952. */
  79953. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  79954. return ConvolutionPostProcess;
  79955. }(BABYLON.PostProcess));
  79956. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  79957. })(BABYLON || (BABYLON = {}));
  79958. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  79959. var BABYLON;
  79960. (function (BABYLON) {
  79961. var FilterPostProcess = /** @class */ (function (_super) {
  79962. __extends(FilterPostProcess, _super);
  79963. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  79964. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  79965. _this.kernelMatrix = kernelMatrix;
  79966. _this.onApply = function (effect) {
  79967. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  79968. };
  79969. return _this;
  79970. }
  79971. return FilterPostProcess;
  79972. }(BABYLON.PostProcess));
  79973. BABYLON.FilterPostProcess = FilterPostProcess;
  79974. })(BABYLON || (BABYLON = {}));
  79975. //# sourceMappingURL=babylon.filterPostProcess.js.map
  79976. var BABYLON;
  79977. (function (BABYLON) {
  79978. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  79979. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  79980. __extends(VolumetricLightScatteringPostProcess, _super);
  79981. /**
  79982. * @constructor
  79983. * @param {string} name - The post-process name
  79984. * @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)
  79985. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  79986. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  79987. * @param {number} samples - The post-process quality, default 100
  79988. * @param {number} samplingMode - The post-process filtering mode
  79989. * @param {BABYLON.Engine} engine - The babylon engine
  79990. * @param {boolean} reusable - If the post-process is reusable
  79991. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  79992. */
  79993. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  79994. if (samples === void 0) { samples = 100; }
  79995. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79996. 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;
  79997. _this._screenCoordinates = BABYLON.Vector2.Zero();
  79998. /**
  79999. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  80000. */
  80001. _this.customMeshPosition = BABYLON.Vector3.Zero();
  80002. /**
  80003. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  80004. */
  80005. _this.useCustomMeshPosition = false;
  80006. /**
  80007. * If the post-process should inverse the light scattering direction
  80008. */
  80009. _this.invert = true;
  80010. /**
  80011. * Array containing the excluded meshes not rendered in the internal pass
  80012. */
  80013. _this.excludedMeshes = new Array();
  80014. /**
  80015. * Controls the overall intensity of the post-process
  80016. */
  80017. _this.exposure = 0.3;
  80018. /**
  80019. * Dissipates each sample's contribution in range [0, 1]
  80020. */
  80021. _this.decay = 0.96815;
  80022. /**
  80023. * Controls the overall intensity of each sample
  80024. */
  80025. _this.weight = 0.58767;
  80026. /**
  80027. * Controls the density of each sample
  80028. */
  80029. _this.density = 0.926;
  80030. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  80031. engine = scene.getEngine();
  80032. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  80033. // Configure mesh
  80034. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  80035. // Configure
  80036. _this._createPass(scene, ratio.passRatio || ratio);
  80037. _this.onActivate = function (camera) {
  80038. if (!_this.isSupported) {
  80039. _this.dispose(camera);
  80040. }
  80041. _this.onActivate = null;
  80042. };
  80043. _this.onApplyObservable.add(function (effect) {
  80044. _this._updateMeshScreenCoordinates(scene);
  80045. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  80046. effect.setFloat("exposure", _this.exposure);
  80047. effect.setFloat("decay", _this.decay);
  80048. effect.setFloat("weight", _this.weight);
  80049. effect.setFloat("density", _this.density);
  80050. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  80051. });
  80052. return _this;
  80053. }
  80054. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  80055. get: function () {
  80056. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  80057. return false;
  80058. },
  80059. set: function (useDiffuseColor) {
  80060. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  80061. },
  80062. enumerable: true,
  80063. configurable: true
  80064. });
  80065. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  80066. return "VolumetricLightScatteringPostProcess";
  80067. };
  80068. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  80069. var mesh = subMesh.getMesh();
  80070. // Render this.mesh as default
  80071. if (mesh === this.mesh && mesh.material) {
  80072. return mesh.material.isReady(mesh);
  80073. }
  80074. var defines = [];
  80075. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80076. var material = subMesh.getMaterial();
  80077. // Alpha test
  80078. if (material) {
  80079. if (material.needAlphaTesting()) {
  80080. defines.push("#define ALPHATEST");
  80081. }
  80082. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80083. attribs.push(BABYLON.VertexBuffer.UVKind);
  80084. defines.push("#define UV1");
  80085. }
  80086. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80087. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80088. defines.push("#define UV2");
  80089. }
  80090. }
  80091. // Bones
  80092. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80093. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80094. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80095. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80096. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80097. }
  80098. else {
  80099. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80100. }
  80101. // Instances
  80102. if (useInstances) {
  80103. defines.push("#define INSTANCES");
  80104. attribs.push("world0");
  80105. attribs.push("world1");
  80106. attribs.push("world2");
  80107. attribs.push("world3");
  80108. }
  80109. // Get correct effect
  80110. var join = defines.join("\n");
  80111. if (this._cachedDefines !== join) {
  80112. this._cachedDefines = join;
  80113. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  80114. }
  80115. return this._volumetricLightScatteringPass.isReady();
  80116. };
  80117. /**
  80118. * Sets the new light position for light scattering effect
  80119. * @param {BABYLON.Vector3} The new custom light position
  80120. */
  80121. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  80122. this.customMeshPosition = position;
  80123. };
  80124. /**
  80125. * Returns the light position for light scattering effect
  80126. * @return {BABYLON.Vector3} The custom light position
  80127. */
  80128. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  80129. return this.customMeshPosition;
  80130. };
  80131. /**
  80132. * Disposes the internal assets and detaches the post-process from the camera
  80133. */
  80134. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  80135. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  80136. if (rttIndex !== -1) {
  80137. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  80138. }
  80139. this._volumetricLightScatteringRTT.dispose();
  80140. _super.prototype.dispose.call(this, camera);
  80141. };
  80142. /**
  80143. * Returns the render target texture used by the post-process
  80144. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  80145. */
  80146. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  80147. return this._volumetricLightScatteringRTT;
  80148. };
  80149. // Private methods
  80150. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  80151. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  80152. return true;
  80153. }
  80154. return false;
  80155. };
  80156. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  80157. var _this = this;
  80158. var engine = scene.getEngine();
  80159. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80160. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80161. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80162. this._volumetricLightScatteringRTT.renderList = null;
  80163. this._volumetricLightScatteringRTT.renderParticles = false;
  80164. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  80165. var camera = this.getCamera();
  80166. if (camera) {
  80167. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80168. }
  80169. else {
  80170. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80171. }
  80172. // Custom render function for submeshes
  80173. var renderSubMesh = function (subMesh) {
  80174. var mesh = subMesh.getRenderingMesh();
  80175. if (_this._meshExcluded(mesh)) {
  80176. return;
  80177. }
  80178. var material = subMesh.getMaterial();
  80179. if (!material) {
  80180. return;
  80181. }
  80182. var scene = mesh.getScene();
  80183. var engine = scene.getEngine();
  80184. // Culling
  80185. engine.setState(material.backFaceCulling);
  80186. // Managing instances
  80187. var batch = mesh._getInstancesRenderList(subMesh._id);
  80188. if (batch.mustReturn) {
  80189. return;
  80190. }
  80191. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80192. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  80193. var effect = _this._volumetricLightScatteringPass;
  80194. if (mesh === _this.mesh) {
  80195. if (subMesh.effect) {
  80196. effect = subMesh.effect;
  80197. }
  80198. else {
  80199. effect = material.getEffect();
  80200. }
  80201. }
  80202. engine.enableEffect(effect);
  80203. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  80204. if (mesh === _this.mesh) {
  80205. material.bind(mesh.getWorldMatrix(), mesh);
  80206. }
  80207. else {
  80208. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  80209. // Alpha test
  80210. if (material && material.needAlphaTesting()) {
  80211. var alphaTexture = material.getAlphaTestTexture();
  80212. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  80213. if (alphaTexture) {
  80214. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80215. }
  80216. }
  80217. // Bones
  80218. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80219. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80220. }
  80221. }
  80222. // Draw
  80223. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  80224. }
  80225. };
  80226. // Render target texture callbacks
  80227. var savedSceneClearColor;
  80228. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  80229. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  80230. savedSceneClearColor = scene.clearColor;
  80231. scene.clearColor = sceneClearColor;
  80232. });
  80233. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  80234. scene.clearColor = savedSceneClearColor;
  80235. });
  80236. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80237. var engine = scene.getEngine();
  80238. var index;
  80239. if (depthOnlySubMeshes.length) {
  80240. engine.setColorWrite(false);
  80241. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80242. renderSubMesh(depthOnlySubMeshes.data[index]);
  80243. }
  80244. engine.setColorWrite(true);
  80245. }
  80246. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80247. renderSubMesh(opaqueSubMeshes.data[index]);
  80248. }
  80249. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80250. renderSubMesh(alphaTestSubMeshes.data[index]);
  80251. }
  80252. if (transparentSubMeshes.length) {
  80253. // Sort sub meshes
  80254. for (index = 0; index < transparentSubMeshes.length; index++) {
  80255. var submesh = transparentSubMeshes.data[index];
  80256. var boundingInfo = submesh.getBoundingInfo();
  80257. if (boundingInfo && scene.activeCamera) {
  80258. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  80259. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  80260. }
  80261. }
  80262. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  80263. sortedArray.sort(function (a, b) {
  80264. // Alpha index first
  80265. if (a._alphaIndex > b._alphaIndex) {
  80266. return 1;
  80267. }
  80268. if (a._alphaIndex < b._alphaIndex) {
  80269. return -1;
  80270. }
  80271. // Then distance to camera
  80272. if (a._distanceToCamera < b._distanceToCamera) {
  80273. return 1;
  80274. }
  80275. if (a._distanceToCamera > b._distanceToCamera) {
  80276. return -1;
  80277. }
  80278. return 0;
  80279. });
  80280. // Render sub meshes
  80281. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  80282. for (index = 0; index < sortedArray.length; index++) {
  80283. renderSubMesh(sortedArray[index]);
  80284. }
  80285. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80286. }
  80287. };
  80288. };
  80289. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  80290. var transform = scene.getTransformMatrix();
  80291. var meshPosition;
  80292. if (this.useCustomMeshPosition) {
  80293. meshPosition = this.customMeshPosition;
  80294. }
  80295. else if (this.attachedNode) {
  80296. meshPosition = this.attachedNode.position;
  80297. }
  80298. else {
  80299. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  80300. }
  80301. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  80302. this._screenCoordinates.x = pos.x / this._viewPort.width;
  80303. this._screenCoordinates.y = pos.y / this._viewPort.height;
  80304. if (this.invert)
  80305. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  80306. };
  80307. // Static methods
  80308. /**
  80309. * Creates a default mesh for the Volumeric Light Scattering post-process
  80310. * @param {string} The mesh name
  80311. * @param {BABYLON.Scene} The scene where to create the mesh
  80312. * @return {BABYLON.Mesh} the default mesh
  80313. */
  80314. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  80315. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  80316. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  80317. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  80318. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  80319. mesh.material = material;
  80320. return mesh;
  80321. };
  80322. __decorate([
  80323. BABYLON.serializeAsVector3()
  80324. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  80325. __decorate([
  80326. BABYLON.serialize()
  80327. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  80328. __decorate([
  80329. BABYLON.serialize()
  80330. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  80331. __decorate([
  80332. BABYLON.serializeAsMeshReference()
  80333. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  80334. __decorate([
  80335. BABYLON.serialize()
  80336. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  80337. __decorate([
  80338. BABYLON.serialize()
  80339. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  80340. __decorate([
  80341. BABYLON.serialize()
  80342. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  80343. __decorate([
  80344. BABYLON.serialize()
  80345. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  80346. __decorate([
  80347. BABYLON.serialize()
  80348. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  80349. return VolumetricLightScatteringPostProcess;
  80350. }(BABYLON.PostProcess));
  80351. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  80352. })(BABYLON || (BABYLON = {}));
  80353. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  80354. //
  80355. // This post-process allows the modification of rendered colors by using
  80356. // a 'look-up table' (LUT). This effect is also called Color Grading.
  80357. //
  80358. // The object needs to be provided an url to a texture containing the color
  80359. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  80360. // Use an image editing software to tweak the LUT to match your needs.
  80361. //
  80362. // For an example of a color LUT, see here:
  80363. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  80364. // For explanations on color grading, see here:
  80365. // http://udn.epicgames.com/Three/ColorGrading.html
  80366. //
  80367. var BABYLON;
  80368. (function (BABYLON) {
  80369. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  80370. __extends(ColorCorrectionPostProcess, _super);
  80371. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  80372. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  80373. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80374. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  80375. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80376. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80377. _this.onApply = function (effect) {
  80378. effect.setTexture("colorTable", _this._colorTableTexture);
  80379. };
  80380. return _this;
  80381. }
  80382. return ColorCorrectionPostProcess;
  80383. }(BABYLON.PostProcess));
  80384. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  80385. })(BABYLON || (BABYLON = {}));
  80386. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  80387. var BABYLON;
  80388. (function (BABYLON) {
  80389. /** Defines operator used for tonemapping */
  80390. var TonemappingOperator;
  80391. (function (TonemappingOperator) {
  80392. /** Hable */
  80393. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  80394. /** Reinhard */
  80395. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  80396. /** HejiDawson */
  80397. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  80398. /** Photographic */
  80399. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  80400. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  80401. ;
  80402. /**
  80403. * Defines a post process to apply tone mapping
  80404. */
  80405. var TonemapPostProcess = /** @class */ (function (_super) {
  80406. __extends(TonemapPostProcess, _super);
  80407. /**
  80408. * Creates a new TonemapPostProcess
  80409. * @param name defines the name of the postprocess
  80410. * @param _operator defines the operator to use
  80411. * @param exposureAdjustment defines the required exposure adjustement
  80412. * @param camera defines the camera to use (can be null)
  80413. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  80414. * @param engine defines the hosting engine (can be ignore if camera is set)
  80415. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  80416. */
  80417. function TonemapPostProcess(name, _operator,
  80418. /** Defines the required exposure adjustement */
  80419. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  80420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80421. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80422. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  80423. _this._operator = _operator;
  80424. _this.exposureAdjustment = exposureAdjustment;
  80425. var defines = "#define ";
  80426. if (_this._operator === TonemappingOperator.Hable)
  80427. defines += "HABLE_TONEMAPPING";
  80428. else if (_this._operator === TonemappingOperator.Reinhard)
  80429. defines += "REINHARD_TONEMAPPING";
  80430. else if (_this._operator === TonemappingOperator.HejiDawson)
  80431. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  80432. else if (_this._operator === TonemappingOperator.Photographic)
  80433. defines += "PHOTOGRAPHIC_TONEMAPPING";
  80434. //sadly a second call to create the effect.
  80435. _this.updateEffect(defines);
  80436. _this.onApply = function (effect) {
  80437. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  80438. };
  80439. return _this;
  80440. }
  80441. return TonemapPostProcess;
  80442. }(BABYLON.PostProcess));
  80443. BABYLON.TonemapPostProcess = TonemapPostProcess;
  80444. })(BABYLON || (BABYLON = {}));
  80445. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  80446. var BABYLON;
  80447. (function (BABYLON) {
  80448. var DisplayPassPostProcess = /** @class */ (function (_super) {
  80449. __extends(DisplayPassPostProcess, _super);
  80450. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  80451. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  80452. }
  80453. return DisplayPassPostProcess;
  80454. }(BABYLON.PostProcess));
  80455. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  80456. })(BABYLON || (BABYLON = {}));
  80457. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  80458. var BABYLON;
  80459. (function (BABYLON) {
  80460. var HighlightsPostProcess = /** @class */ (function (_super) {
  80461. __extends(HighlightsPostProcess, _super);
  80462. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80463. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80464. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80465. }
  80466. return HighlightsPostProcess;
  80467. }(BABYLON.PostProcess));
  80468. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  80469. })(BABYLON || (BABYLON = {}));
  80470. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  80471. var BABYLON;
  80472. (function (BABYLON) {
  80473. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  80474. __extends(ImageProcessingPostProcess, _super);
  80475. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  80476. if (camera === void 0) { camera = null; }
  80477. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80478. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  80479. _this._fromLinearSpace = true;
  80480. /**
  80481. * Defines cache preventing GC.
  80482. */
  80483. _this._defines = {
  80484. IMAGEPROCESSING: false,
  80485. VIGNETTE: false,
  80486. VIGNETTEBLENDMODEMULTIPLY: false,
  80487. VIGNETTEBLENDMODEOPAQUE: false,
  80488. TONEMAPPING: false,
  80489. CONTRAST: false,
  80490. COLORCURVES: false,
  80491. COLORGRADING: false,
  80492. COLORGRADING3D: false,
  80493. FROMLINEARSPACE: false,
  80494. SAMPLER3DGREENDEPTH: false,
  80495. SAMPLER3DBGRMAP: false,
  80496. IMAGEPROCESSINGPOSTPROCESS: false,
  80497. EXPOSURE: false,
  80498. };
  80499. // Setup the configuration as forced by the constructor. This would then not force the
  80500. // scene materials output in linear space and let untouched the default forward pass.
  80501. if (imageProcessingConfiguration) {
  80502. imageProcessingConfiguration.applyByPostProcess = true;
  80503. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  80504. // This will cause the shader to be compiled
  80505. _this.fromLinearSpace = false;
  80506. }
  80507. // Setup the default processing configuration to the scene.
  80508. else {
  80509. _this._attachImageProcessingConfiguration(null, true);
  80510. _this.imageProcessingConfiguration.applyByPostProcess = true;
  80511. }
  80512. _this.onApply = function (effect) {
  80513. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  80514. };
  80515. return _this;
  80516. }
  80517. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  80518. /**
  80519. * Gets the image processing configuration used either in this material.
  80520. */
  80521. get: function () {
  80522. return this._imageProcessingConfiguration;
  80523. },
  80524. /**
  80525. * Sets the Default image processing configuration used either in the this material.
  80526. *
  80527. * If sets to null, the scene one is in use.
  80528. */
  80529. set: function (value) {
  80530. this._attachImageProcessingConfiguration(value);
  80531. },
  80532. enumerable: true,
  80533. configurable: true
  80534. });
  80535. /**
  80536. * Attaches a new image processing configuration to the PBR Material.
  80537. * @param configuration
  80538. */
  80539. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  80540. var _this = this;
  80541. if (doNotBuild === void 0) { doNotBuild = false; }
  80542. if (configuration === this._imageProcessingConfiguration) {
  80543. return;
  80544. }
  80545. // Detaches observer.
  80546. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80547. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80548. }
  80549. // Pick the scene configuration if needed.
  80550. if (!configuration) {
  80551. var scene = null;
  80552. var engine = this.getEngine();
  80553. var camera = this.getCamera();
  80554. if (camera) {
  80555. scene = camera.getScene();
  80556. }
  80557. else if (engine && engine.scenes) {
  80558. var scenes = engine.scenes;
  80559. scene = scenes[scenes.length - 1];
  80560. }
  80561. else {
  80562. scene = BABYLON.Engine.LastCreatedScene;
  80563. }
  80564. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  80565. }
  80566. else {
  80567. this._imageProcessingConfiguration = configuration;
  80568. }
  80569. // Attaches observer.
  80570. if (this._imageProcessingConfiguration) {
  80571. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80572. _this._updateParameters();
  80573. });
  80574. }
  80575. // Ensure the effect will be rebuilt.
  80576. if (!doNotBuild) {
  80577. this._updateParameters();
  80578. }
  80579. };
  80580. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  80581. /**
  80582. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80583. */
  80584. get: function () {
  80585. return this.imageProcessingConfiguration.colorCurves;
  80586. },
  80587. /**
  80588. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80589. */
  80590. set: function (value) {
  80591. this.imageProcessingConfiguration.colorCurves = value;
  80592. },
  80593. enumerable: true,
  80594. configurable: true
  80595. });
  80596. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  80597. /**
  80598. * Gets wether the color curves effect is enabled.
  80599. */
  80600. get: function () {
  80601. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80602. },
  80603. /**
  80604. * Sets wether the color curves effect is enabled.
  80605. */
  80606. set: function (value) {
  80607. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80608. },
  80609. enumerable: true,
  80610. configurable: true
  80611. });
  80612. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  80613. /**
  80614. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80615. */
  80616. get: function () {
  80617. return this.imageProcessingConfiguration.colorGradingTexture;
  80618. },
  80619. /**
  80620. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80621. */
  80622. set: function (value) {
  80623. this.imageProcessingConfiguration.colorGradingTexture = value;
  80624. },
  80625. enumerable: true,
  80626. configurable: true
  80627. });
  80628. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  80629. /**
  80630. * Gets wether the color grading effect is enabled.
  80631. */
  80632. get: function () {
  80633. return this.imageProcessingConfiguration.colorGradingEnabled;
  80634. },
  80635. /**
  80636. * Gets wether the color grading effect is enabled.
  80637. */
  80638. set: function (value) {
  80639. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80640. },
  80641. enumerable: true,
  80642. configurable: true
  80643. });
  80644. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  80645. /**
  80646. * Gets exposure used in the effect.
  80647. */
  80648. get: function () {
  80649. return this.imageProcessingConfiguration.exposure;
  80650. },
  80651. /**
  80652. * Sets exposure used in the effect.
  80653. */
  80654. set: function (value) {
  80655. this.imageProcessingConfiguration.exposure = value;
  80656. },
  80657. enumerable: true,
  80658. configurable: true
  80659. });
  80660. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  80661. /**
  80662. * Gets wether tonemapping is enabled or not.
  80663. */
  80664. get: function () {
  80665. return this._imageProcessingConfiguration.toneMappingEnabled;
  80666. },
  80667. /**
  80668. * Sets wether tonemapping is enabled or not
  80669. */
  80670. set: function (value) {
  80671. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80672. },
  80673. enumerable: true,
  80674. configurable: true
  80675. });
  80676. ;
  80677. ;
  80678. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  80679. /**
  80680. * Gets contrast used in the effect.
  80681. */
  80682. get: function () {
  80683. return this.imageProcessingConfiguration.contrast;
  80684. },
  80685. /**
  80686. * Sets contrast used in the effect.
  80687. */
  80688. set: function (value) {
  80689. this.imageProcessingConfiguration.contrast = value;
  80690. },
  80691. enumerable: true,
  80692. configurable: true
  80693. });
  80694. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  80695. /**
  80696. * Gets Vignette stretch size.
  80697. */
  80698. get: function () {
  80699. return this.imageProcessingConfiguration.vignetteStretch;
  80700. },
  80701. /**
  80702. * Sets Vignette stretch size.
  80703. */
  80704. set: function (value) {
  80705. this.imageProcessingConfiguration.vignetteStretch = value;
  80706. },
  80707. enumerable: true,
  80708. configurable: true
  80709. });
  80710. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  80711. /**
  80712. * Gets Vignette centre X Offset.
  80713. */
  80714. get: function () {
  80715. return this.imageProcessingConfiguration.vignetteCentreX;
  80716. },
  80717. /**
  80718. * Sets Vignette centre X Offset.
  80719. */
  80720. set: function (value) {
  80721. this.imageProcessingConfiguration.vignetteCentreX = value;
  80722. },
  80723. enumerable: true,
  80724. configurable: true
  80725. });
  80726. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  80727. /**
  80728. * Gets Vignette centre Y Offset.
  80729. */
  80730. get: function () {
  80731. return this.imageProcessingConfiguration.vignetteCentreY;
  80732. },
  80733. /**
  80734. * Sets Vignette centre Y Offset.
  80735. */
  80736. set: function (value) {
  80737. this.imageProcessingConfiguration.vignetteCentreY = value;
  80738. },
  80739. enumerable: true,
  80740. configurable: true
  80741. });
  80742. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  80743. /**
  80744. * Gets Vignette weight or intensity of the vignette effect.
  80745. */
  80746. get: function () {
  80747. return this.imageProcessingConfiguration.vignetteWeight;
  80748. },
  80749. /**
  80750. * Sets Vignette weight or intensity of the vignette effect.
  80751. */
  80752. set: function (value) {
  80753. this.imageProcessingConfiguration.vignetteWeight = value;
  80754. },
  80755. enumerable: true,
  80756. configurable: true
  80757. });
  80758. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  80759. /**
  80760. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80761. * if vignetteEnabled is set to true.
  80762. */
  80763. get: function () {
  80764. return this.imageProcessingConfiguration.vignetteColor;
  80765. },
  80766. /**
  80767. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80768. * if vignetteEnabled is set to true.
  80769. */
  80770. set: function (value) {
  80771. this.imageProcessingConfiguration.vignetteColor = value;
  80772. },
  80773. enumerable: true,
  80774. configurable: true
  80775. });
  80776. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  80777. /**
  80778. * Gets Camera field of view used by the Vignette effect.
  80779. */
  80780. get: function () {
  80781. return this.imageProcessingConfiguration.vignetteCameraFov;
  80782. },
  80783. /**
  80784. * Sets Camera field of view used by the Vignette effect.
  80785. */
  80786. set: function (value) {
  80787. this.imageProcessingConfiguration.vignetteCameraFov = value;
  80788. },
  80789. enumerable: true,
  80790. configurable: true
  80791. });
  80792. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  80793. /**
  80794. * Gets the vignette blend mode allowing different kind of effect.
  80795. */
  80796. get: function () {
  80797. return this.imageProcessingConfiguration.vignetteBlendMode;
  80798. },
  80799. /**
  80800. * Sets the vignette blend mode allowing different kind of effect.
  80801. */
  80802. set: function (value) {
  80803. this.imageProcessingConfiguration.vignetteBlendMode = value;
  80804. },
  80805. enumerable: true,
  80806. configurable: true
  80807. });
  80808. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  80809. /**
  80810. * Gets wether the vignette effect is enabled.
  80811. */
  80812. get: function () {
  80813. return this.imageProcessingConfiguration.vignetteEnabled;
  80814. },
  80815. /**
  80816. * Sets wether the vignette effect is enabled.
  80817. */
  80818. set: function (value) {
  80819. this.imageProcessingConfiguration.vignetteEnabled = value;
  80820. },
  80821. enumerable: true,
  80822. configurable: true
  80823. });
  80824. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  80825. /**
  80826. * Gets wether the input of the processing is in Gamma or Linear Space.
  80827. */
  80828. get: function () {
  80829. return this._fromLinearSpace;
  80830. },
  80831. /**
  80832. * Sets wether the input of the processing is in Gamma or Linear Space.
  80833. */
  80834. set: function (value) {
  80835. if (this._fromLinearSpace === value) {
  80836. return;
  80837. }
  80838. this._fromLinearSpace = value;
  80839. this._updateParameters();
  80840. },
  80841. enumerable: true,
  80842. configurable: true
  80843. });
  80844. ImageProcessingPostProcess.prototype.getClassName = function () {
  80845. return "ImageProcessingPostProcess";
  80846. };
  80847. ImageProcessingPostProcess.prototype._updateParameters = function () {
  80848. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  80849. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  80850. var defines = "";
  80851. for (var define in this._defines) {
  80852. if (this._defines[define]) {
  80853. defines += "#define " + define + ";\r\n";
  80854. }
  80855. }
  80856. var samplers = ["textureSampler"];
  80857. var uniforms = ["scale"];
  80858. if (BABYLON.ImageProcessingConfiguration) {
  80859. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  80860. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  80861. }
  80862. this.updateEffect(defines, uniforms, samplers);
  80863. };
  80864. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  80865. _super.prototype.dispose.call(this, camera);
  80866. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80867. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80868. }
  80869. if (this._imageProcessingConfiguration) {
  80870. this.imageProcessingConfiguration.applyByPostProcess = false;
  80871. }
  80872. };
  80873. __decorate([
  80874. BABYLON.serialize()
  80875. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  80876. return ImageProcessingPostProcess;
  80877. }(BABYLON.PostProcess));
  80878. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  80879. })(BABYLON || (BABYLON = {}));
  80880. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  80881. var BABYLON;
  80882. (function (BABYLON) {
  80883. /**
  80884. * Class used to store bone information
  80885. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80886. */
  80887. var Bone = /** @class */ (function (_super) {
  80888. __extends(Bone, _super);
  80889. /**
  80890. * Create a new bone
  80891. * @param name defines the bone name
  80892. * @param skeleton defines the parent skeleton
  80893. * @param parentBone defines the parent (can be null if the bone is the root)
  80894. * @param localMatrix defines the local matrix
  80895. * @param restPose defines the rest pose matrix
  80896. * @param baseMatrix defines the base matrix
  80897. * @param index defines index of the bone in the hiearchy
  80898. */
  80899. function Bone(
  80900. /**
  80901. * defines the bone name
  80902. */
  80903. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  80904. if (parentBone === void 0) { parentBone = null; }
  80905. if (localMatrix === void 0) { localMatrix = null; }
  80906. if (restPose === void 0) { restPose = null; }
  80907. if (baseMatrix === void 0) { baseMatrix = null; }
  80908. if (index === void 0) { index = null; }
  80909. var _this = _super.call(this, name, skeleton.getScene()) || this;
  80910. _this.name = name;
  80911. /**
  80912. * Gets the list of child bones
  80913. */
  80914. _this.children = new Array();
  80915. /** Gets the animations associated with this bone */
  80916. _this.animations = new Array();
  80917. /**
  80918. * @hidden Internal only
  80919. * Set this value to map this bone to a different index in the transform matrices
  80920. * Set this value to -1 to exclude the bone from the transform matrices
  80921. */
  80922. _this._index = null;
  80923. _this._absoluteTransform = new BABYLON.Matrix();
  80924. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  80925. _this._scalingDeterminant = 1;
  80926. _this._worldTransform = new BABYLON.Matrix();
  80927. _this._needToDecompose = true;
  80928. _this._needToCompose = false;
  80929. _this._skeleton = skeleton;
  80930. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  80931. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  80932. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  80933. _this._index = index;
  80934. skeleton.bones.push(_this);
  80935. _this.setParent(parentBone, false);
  80936. if (baseMatrix || localMatrix) {
  80937. _this._updateDifferenceMatrix();
  80938. }
  80939. return _this;
  80940. }
  80941. Object.defineProperty(Bone.prototype, "_matrix", {
  80942. /** @hidden */
  80943. get: function () {
  80944. this._compose();
  80945. return this._localMatrix;
  80946. },
  80947. /** @hidden */
  80948. set: function (value) {
  80949. this._localMatrix.copyFrom(value);
  80950. this._needToDecompose = true;
  80951. },
  80952. enumerable: true,
  80953. configurable: true
  80954. });
  80955. // Members
  80956. /**
  80957. * Gets the parent skeleton
  80958. * @returns a skeleton
  80959. */
  80960. Bone.prototype.getSkeleton = function () {
  80961. return this._skeleton;
  80962. };
  80963. /**
  80964. * Gets parent bone
  80965. * @returns a bone or null if the bone is the root of the bone hierarchy
  80966. */
  80967. Bone.prototype.getParent = function () {
  80968. return this._parent;
  80969. };
  80970. /**
  80971. * Sets the parent bone
  80972. * @param parent defines the parent (can be null if the bone is the root)
  80973. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80974. */
  80975. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  80976. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80977. if (this._parent === parent) {
  80978. return;
  80979. }
  80980. if (this._parent) {
  80981. var index = this._parent.children.indexOf(this);
  80982. if (index !== -1) {
  80983. this._parent.children.splice(index, 1);
  80984. }
  80985. }
  80986. this._parent = parent;
  80987. if (this._parent) {
  80988. this._parent.children.push(this);
  80989. }
  80990. if (updateDifferenceMatrix) {
  80991. this._updateDifferenceMatrix();
  80992. }
  80993. this.markAsDirty();
  80994. };
  80995. /**
  80996. * Gets the local matrix
  80997. * @returns a matrix
  80998. */
  80999. Bone.prototype.getLocalMatrix = function () {
  81000. this._compose();
  81001. return this._localMatrix;
  81002. };
  81003. /**
  81004. * Gets the base matrix (initial matrix which remains unchanged)
  81005. * @returns a matrix
  81006. */
  81007. Bone.prototype.getBaseMatrix = function () {
  81008. return this._baseMatrix;
  81009. };
  81010. /**
  81011. * Gets the rest pose matrix
  81012. * @returns a matrix
  81013. */
  81014. Bone.prototype.getRestPose = function () {
  81015. return this._restPose;
  81016. };
  81017. /**
  81018. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  81019. */
  81020. Bone.prototype.getWorldMatrix = function () {
  81021. return this._worldTransform;
  81022. };
  81023. /**
  81024. * Sets the local matrix to rest pose matrix
  81025. */
  81026. Bone.prototype.returnToRest = function () {
  81027. this.updateMatrix(this._restPose.clone());
  81028. };
  81029. /**
  81030. * Gets the inverse of the absolute transform matrix.
  81031. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  81032. * @returns a matrix
  81033. */
  81034. Bone.prototype.getInvertedAbsoluteTransform = function () {
  81035. return this._invertedAbsoluteTransform;
  81036. };
  81037. /**
  81038. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  81039. * @returns a matrix
  81040. */
  81041. Bone.prototype.getAbsoluteTransform = function () {
  81042. return this._absoluteTransform;
  81043. };
  81044. Object.defineProperty(Bone.prototype, "position", {
  81045. // Properties (matches AbstractMesh properties)
  81046. /** Gets or sets current position (in local space) */
  81047. get: function () {
  81048. this._decompose();
  81049. return this._localPosition;
  81050. },
  81051. set: function (newPosition) {
  81052. this._decompose();
  81053. this._localPosition.copyFrom(newPosition);
  81054. this._markAsDirtyAndCompose();
  81055. },
  81056. enumerable: true,
  81057. configurable: true
  81058. });
  81059. Object.defineProperty(Bone.prototype, "rotation", {
  81060. /** Gets or sets current rotation (in local space) */
  81061. get: function () {
  81062. return this.getRotation();
  81063. },
  81064. set: function (newRotation) {
  81065. this.setRotation(newRotation);
  81066. },
  81067. enumerable: true,
  81068. configurable: true
  81069. });
  81070. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  81071. /** Gets or sets current rotation quaternion (in local space) */
  81072. get: function () {
  81073. this._decompose();
  81074. return this._localRotation;
  81075. },
  81076. set: function (newRotation) {
  81077. this.setRotationQuaternion(newRotation);
  81078. },
  81079. enumerable: true,
  81080. configurable: true
  81081. });
  81082. Object.defineProperty(Bone.prototype, "scaling", {
  81083. /** Gets or sets current scaling (in local space) */
  81084. get: function () {
  81085. return this.getScale();
  81086. },
  81087. set: function (newScaling) {
  81088. this.setScale(newScaling);
  81089. },
  81090. enumerable: true,
  81091. configurable: true
  81092. });
  81093. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  81094. /**
  81095. * Gets the animation properties override
  81096. */
  81097. get: function () {
  81098. return this._skeleton.animationPropertiesOverride;
  81099. },
  81100. enumerable: true,
  81101. configurable: true
  81102. });
  81103. // Methods
  81104. Bone.prototype._decompose = function () {
  81105. if (!this._needToDecompose) {
  81106. return;
  81107. }
  81108. this._needToDecompose = false;
  81109. if (!this._localScaling) {
  81110. this._localScaling = BABYLON.Vector3.Zero();
  81111. this._localRotation = BABYLON.Quaternion.Zero();
  81112. this._localPosition = BABYLON.Vector3.Zero();
  81113. }
  81114. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  81115. };
  81116. Bone.prototype._compose = function () {
  81117. if (!this._needToCompose) {
  81118. return;
  81119. }
  81120. this._needToCompose = false;
  81121. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  81122. };
  81123. /**
  81124. * Update the base and local matrices
  81125. * @param matrix defines the new base or local matrix
  81126. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  81127. * @param updateLocalMatrix defines if the local matrix should be updated
  81128. */
  81129. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  81130. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  81131. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  81132. this._baseMatrix.copyFrom(matrix);
  81133. if (updateDifferenceMatrix) {
  81134. this._updateDifferenceMatrix();
  81135. }
  81136. if (updateLocalMatrix) {
  81137. this._localMatrix.copyFrom(matrix);
  81138. this._markAsDirtyAndDecompose();
  81139. }
  81140. else {
  81141. this.markAsDirty();
  81142. }
  81143. };
  81144. /** @hidden */
  81145. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  81146. if (updateChildren === void 0) { updateChildren = true; }
  81147. if (!rootMatrix) {
  81148. rootMatrix = this._baseMatrix;
  81149. }
  81150. if (this._parent) {
  81151. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81152. }
  81153. else {
  81154. this._absoluteTransform.copyFrom(rootMatrix);
  81155. }
  81156. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  81157. if (updateChildren) {
  81158. for (var index = 0; index < this.children.length; index++) {
  81159. this.children[index]._updateDifferenceMatrix();
  81160. }
  81161. }
  81162. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  81163. };
  81164. /**
  81165. * Flag the bone as dirty (Forcing it to update everything)
  81166. */
  81167. Bone.prototype.markAsDirty = function () {
  81168. this._currentRenderId++;
  81169. this._childRenderId++;
  81170. this._skeleton._markAsDirty();
  81171. };
  81172. Bone.prototype._markAsDirtyAndCompose = function () {
  81173. this.markAsDirty();
  81174. this._needToCompose = true;
  81175. };
  81176. Bone.prototype._markAsDirtyAndDecompose = function () {
  81177. this.markAsDirty();
  81178. this._needToDecompose = true;
  81179. };
  81180. /**
  81181. * Copy an animation range from another bone
  81182. * @param source defines the source bone
  81183. * @param rangeName defines the range name to copy
  81184. * @param frameOffset defines the frame offset
  81185. * @param rescaleAsRequired defines if rescaling must be applied if required
  81186. * @param skelDimensionsRatio defines the scaling ratio
  81187. * @returns true if operation was successful
  81188. */
  81189. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  81190. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81191. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  81192. // all animation may be coming from a library skeleton, so may need to create animation
  81193. if (this.animations.length === 0) {
  81194. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  81195. this.animations[0].setKeys([]);
  81196. }
  81197. // get animation info / verify there is such a range from the source bone
  81198. var sourceRange = source.animations[0].getRange(rangeName);
  81199. if (!sourceRange) {
  81200. return false;
  81201. }
  81202. var from = sourceRange.from;
  81203. var to = sourceRange.to;
  81204. var sourceKeys = source.animations[0].getKeys();
  81205. // rescaling prep
  81206. var sourceBoneLength = source.length;
  81207. var sourceParent = source.getParent();
  81208. var parent = this.getParent();
  81209. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  81210. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  81211. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  81212. var destKeys = this.animations[0].getKeys();
  81213. // loop vars declaration
  81214. var orig;
  81215. var origTranslation;
  81216. var mat;
  81217. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  81218. orig = sourceKeys[key];
  81219. if (orig.frame >= from && orig.frame <= to) {
  81220. if (rescaleAsRequired) {
  81221. mat = orig.value.clone();
  81222. // scale based on parent ratio, when bone has parent
  81223. if (parentScalingReqd) {
  81224. origTranslation = mat.getTranslation();
  81225. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  81226. // scale based on skeleton dimension ratio when root bone, and value is passed
  81227. }
  81228. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  81229. origTranslation = mat.getTranslation();
  81230. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  81231. // use original when root bone, and no data for skelDimensionsRatio
  81232. }
  81233. else {
  81234. mat = orig.value;
  81235. }
  81236. }
  81237. else {
  81238. mat = orig.value;
  81239. }
  81240. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  81241. }
  81242. }
  81243. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  81244. return true;
  81245. };
  81246. /**
  81247. * Translate the bone in local or world space
  81248. * @param vec The amount to translate the bone
  81249. * @param space The space that the translation is in
  81250. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81251. */
  81252. Bone.prototype.translate = function (vec, space, mesh) {
  81253. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81254. var lm = this.getLocalMatrix();
  81255. if (space == BABYLON.Space.LOCAL) {
  81256. lm.m[12] += vec.x;
  81257. lm.m[13] += vec.y;
  81258. lm.m[14] += vec.z;
  81259. }
  81260. else {
  81261. var wm = null;
  81262. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81263. if (mesh) {
  81264. wm = mesh.getWorldMatrix();
  81265. }
  81266. this._skeleton.computeAbsoluteTransforms();
  81267. var tmat = Bone._tmpMats[0];
  81268. var tvec = Bone._tmpVecs[0];
  81269. if (this._parent) {
  81270. if (mesh && wm) {
  81271. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81272. tmat.multiplyToRef(wm, tmat);
  81273. }
  81274. else {
  81275. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81276. }
  81277. }
  81278. tmat.m[12] = 0;
  81279. tmat.m[13] = 0;
  81280. tmat.m[14] = 0;
  81281. tmat.invert();
  81282. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  81283. lm.m[12] += tvec.x;
  81284. lm.m[13] += tvec.y;
  81285. lm.m[14] += tvec.z;
  81286. }
  81287. this._markAsDirtyAndDecompose();
  81288. };
  81289. /**
  81290. * Set the postion of the bone in local or world space
  81291. * @param position The position to set the bone
  81292. * @param space The space that the position is in
  81293. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81294. */
  81295. Bone.prototype.setPosition = function (position, space, mesh) {
  81296. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81297. var lm = this.getLocalMatrix();
  81298. if (space == BABYLON.Space.LOCAL) {
  81299. lm.m[12] = position.x;
  81300. lm.m[13] = position.y;
  81301. lm.m[14] = position.z;
  81302. }
  81303. else {
  81304. var wm = null;
  81305. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81306. if (mesh) {
  81307. wm = mesh.getWorldMatrix();
  81308. }
  81309. this._skeleton.computeAbsoluteTransforms();
  81310. var tmat = Bone._tmpMats[0];
  81311. var vec = Bone._tmpVecs[0];
  81312. if (this._parent) {
  81313. if (mesh && wm) {
  81314. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81315. tmat.multiplyToRef(wm, tmat);
  81316. }
  81317. else {
  81318. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81319. }
  81320. }
  81321. tmat.invert();
  81322. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  81323. lm.m[12] = vec.x;
  81324. lm.m[13] = vec.y;
  81325. lm.m[14] = vec.z;
  81326. }
  81327. this._markAsDirtyAndDecompose();
  81328. };
  81329. /**
  81330. * Set the absolute position of the bone (world space)
  81331. * @param position The position to set the bone
  81332. * @param mesh The mesh that this bone is attached to
  81333. */
  81334. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  81335. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  81336. };
  81337. /**
  81338. * Scale the bone on the x, y and z axes (in local space)
  81339. * @param x The amount to scale the bone on the x axis
  81340. * @param y The amount to scale the bone on the y axis
  81341. * @param z The amount to scale the bone on the z axis
  81342. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  81343. */
  81344. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  81345. if (scaleChildren === void 0) { scaleChildren = false; }
  81346. var locMat = this.getLocalMatrix();
  81347. // Apply new scaling on top of current local matrix
  81348. var scaleMat = Bone._tmpMats[0];
  81349. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  81350. scaleMat.multiplyToRef(locMat, locMat);
  81351. // Invert scaling matrix and apply the inverse to all children
  81352. scaleMat.invert();
  81353. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  81354. var child = _a[_i];
  81355. var cm = child.getLocalMatrix();
  81356. cm.multiplyToRef(scaleMat, cm);
  81357. cm.m[12] *= x;
  81358. cm.m[13] *= y;
  81359. cm.m[14] *= z;
  81360. child._markAsDirtyAndDecompose();
  81361. }
  81362. this._markAsDirtyAndDecompose();
  81363. if (scaleChildren) {
  81364. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  81365. var child = _c[_b];
  81366. child.scale(x, y, z, scaleChildren);
  81367. }
  81368. }
  81369. };
  81370. /**
  81371. * Set the bone scaling in local space
  81372. * @param scale defines the scaling vector
  81373. */
  81374. Bone.prototype.setScale = function (scale) {
  81375. this._decompose();
  81376. this._localScaling.copyFrom(scale);
  81377. this._markAsDirtyAndCompose();
  81378. };
  81379. /**
  81380. * Gets the current scaling in local space
  81381. * @returns the current scaling vector
  81382. */
  81383. Bone.prototype.getScale = function () {
  81384. this._decompose();
  81385. return this._localScaling;
  81386. };
  81387. /**
  81388. * Gets the current scaling in local space and stores it in a target vector
  81389. * @param result defines the target vector
  81390. */
  81391. Bone.prototype.getScaleToRef = function (result) {
  81392. this._decompose();
  81393. result.copyFrom(this._localScaling);
  81394. };
  81395. /**
  81396. * Set the yaw, pitch, and roll of the bone in local or world space
  81397. * @param yaw The rotation of the bone on the y axis
  81398. * @param pitch The rotation of the bone on the x axis
  81399. * @param roll The rotation of the bone on the z axis
  81400. * @param space The space that the axes of rotation are in
  81401. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81402. */
  81403. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  81404. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81405. if (space === BABYLON.Space.LOCAL) {
  81406. var quat = Bone._tmpQuat;
  81407. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  81408. this.setRotationQuaternion(quat, space, mesh);
  81409. return;
  81410. }
  81411. var rotMatInv = Bone._tmpMats[0];
  81412. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81413. return;
  81414. }
  81415. var rotMat = Bone._tmpMats[1];
  81416. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  81417. rotMatInv.multiplyToRef(rotMat, rotMat);
  81418. this._rotateWithMatrix(rotMat, space, mesh);
  81419. };
  81420. /**
  81421. * Add a rotation to the bone on an axis in local or world space
  81422. * @param axis The axis to rotate the bone on
  81423. * @param amount The amount to rotate the bone
  81424. * @param space The space that the axis is in
  81425. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81426. */
  81427. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  81428. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81429. var rmat = Bone._tmpMats[0];
  81430. rmat.m[12] = 0;
  81431. rmat.m[13] = 0;
  81432. rmat.m[14] = 0;
  81433. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  81434. this._rotateWithMatrix(rmat, space, mesh);
  81435. };
  81436. /**
  81437. * Set the rotation of the bone to a particular axis angle in local or world space
  81438. * @param axis The axis to rotate the bone on
  81439. * @param angle The angle that the bone should be rotated to
  81440. * @param space The space that the axis is in
  81441. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81442. */
  81443. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  81444. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81445. if (space === BABYLON.Space.LOCAL) {
  81446. var quat = Bone._tmpQuat;
  81447. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  81448. this.setRotationQuaternion(quat, space, mesh);
  81449. return;
  81450. }
  81451. var rotMatInv = Bone._tmpMats[0];
  81452. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81453. return;
  81454. }
  81455. var rotMat = Bone._tmpMats[1];
  81456. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  81457. rotMatInv.multiplyToRef(rotMat, rotMat);
  81458. this._rotateWithMatrix(rotMat, space, mesh);
  81459. };
  81460. /**
  81461. * Set the euler rotation of the bone in local of world space
  81462. * @param rotation The euler rotation that the bone should be set to
  81463. * @param space The space that the rotation is in
  81464. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81465. */
  81466. Bone.prototype.setRotation = function (rotation, space, mesh) {
  81467. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81468. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  81469. };
  81470. /**
  81471. * Set the quaternion rotation of the bone in local of world space
  81472. * @param quat The quaternion rotation that the bone should be set to
  81473. * @param space The space that the rotation is in
  81474. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81475. */
  81476. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  81477. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81478. if (space === BABYLON.Space.LOCAL) {
  81479. this._decompose();
  81480. this._localRotation.copyFrom(quat);
  81481. this._markAsDirtyAndCompose();
  81482. return;
  81483. }
  81484. var rotMatInv = Bone._tmpMats[0];
  81485. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81486. return;
  81487. }
  81488. var rotMat = Bone._tmpMats[1];
  81489. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  81490. rotMatInv.multiplyToRef(rotMat, rotMat);
  81491. this._rotateWithMatrix(rotMat, space, mesh);
  81492. };
  81493. /**
  81494. * Set the rotation matrix of the bone in local of world space
  81495. * @param rotMat The rotation matrix that the bone should be set to
  81496. * @param space The space that the rotation is in
  81497. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81498. */
  81499. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  81500. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81501. if (space === BABYLON.Space.LOCAL) {
  81502. var quat = Bone._tmpQuat;
  81503. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  81504. this.setRotationQuaternion(quat, space, mesh);
  81505. return;
  81506. }
  81507. var rotMatInv = Bone._tmpMats[0];
  81508. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81509. return;
  81510. }
  81511. var rotMat2 = Bone._tmpMats[1];
  81512. rotMat2.copyFrom(rotMat);
  81513. rotMatInv.multiplyToRef(rotMat, rotMat2);
  81514. this._rotateWithMatrix(rotMat2, space, mesh);
  81515. };
  81516. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  81517. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81518. var lmat = this.getLocalMatrix();
  81519. var lx = lmat.m[12];
  81520. var ly = lmat.m[13];
  81521. var lz = lmat.m[14];
  81522. var parent = this.getParent();
  81523. var parentScale = Bone._tmpMats[3];
  81524. var parentScaleInv = Bone._tmpMats[4];
  81525. if (parent && space == BABYLON.Space.WORLD) {
  81526. if (mesh) {
  81527. parentScale.copyFrom(mesh.getWorldMatrix());
  81528. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  81529. }
  81530. else {
  81531. parentScale.copyFrom(parent.getAbsoluteTransform());
  81532. }
  81533. parentScaleInv.copyFrom(parentScale);
  81534. parentScaleInv.invert();
  81535. lmat.multiplyToRef(parentScale, lmat);
  81536. lmat.multiplyToRef(rmat, lmat);
  81537. lmat.multiplyToRef(parentScaleInv, lmat);
  81538. }
  81539. else {
  81540. if (space == BABYLON.Space.WORLD && mesh) {
  81541. parentScale.copyFrom(mesh.getWorldMatrix());
  81542. parentScaleInv.copyFrom(parentScale);
  81543. parentScaleInv.invert();
  81544. lmat.multiplyToRef(parentScale, lmat);
  81545. lmat.multiplyToRef(rmat, lmat);
  81546. lmat.multiplyToRef(parentScaleInv, lmat);
  81547. }
  81548. else {
  81549. lmat.multiplyToRef(rmat, lmat);
  81550. }
  81551. }
  81552. lmat.m[12] = lx;
  81553. lmat.m[13] = ly;
  81554. lmat.m[14] = lz;
  81555. this.computeAbsoluteTransforms();
  81556. this._markAsDirtyAndDecompose();
  81557. };
  81558. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  81559. var scaleMatrix = Bone._tmpMats[2];
  81560. rotMatInv.copyFrom(this.getAbsoluteTransform());
  81561. if (mesh) {
  81562. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  81563. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  81564. }
  81565. rotMatInv.invert();
  81566. if (isNaN(rotMatInv.m[0])) {
  81567. // Matrix failed to invert.
  81568. // This can happen if scale is zero for example.
  81569. return false;
  81570. }
  81571. scaleMatrix.m[0] *= this._scalingDeterminant;
  81572. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  81573. return true;
  81574. };
  81575. /**
  81576. * Get the position of the bone in local or world space
  81577. * @param space The space that the returned position is in
  81578. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81579. * @returns The position of the bone
  81580. */
  81581. Bone.prototype.getPosition = function (space, mesh) {
  81582. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81583. if (mesh === void 0) { mesh = null; }
  81584. var pos = BABYLON.Vector3.Zero();
  81585. this.getPositionToRef(space, mesh, pos);
  81586. return pos;
  81587. };
  81588. /**
  81589. * Copy the position of the bone to a vector3 in local or world space
  81590. * @param space The space that the returned position is in
  81591. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81592. * @param result The vector3 to copy the position to
  81593. */
  81594. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  81595. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81596. if (space == BABYLON.Space.LOCAL) {
  81597. var lm = this.getLocalMatrix();
  81598. result.x = lm.m[12];
  81599. result.y = lm.m[13];
  81600. result.z = lm.m[14];
  81601. }
  81602. else {
  81603. var wm = null;
  81604. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81605. if (mesh) {
  81606. wm = mesh.getWorldMatrix();
  81607. }
  81608. this._skeleton.computeAbsoluteTransforms();
  81609. var tmat = Bone._tmpMats[0];
  81610. if (mesh && wm) {
  81611. tmat.copyFrom(this.getAbsoluteTransform());
  81612. tmat.multiplyToRef(wm, tmat);
  81613. }
  81614. else {
  81615. tmat = this.getAbsoluteTransform();
  81616. }
  81617. result.x = tmat.m[12];
  81618. result.y = tmat.m[13];
  81619. result.z = tmat.m[14];
  81620. }
  81621. };
  81622. /**
  81623. * Get the absolute position of the bone (world space)
  81624. * @param mesh The mesh that this bone is attached to
  81625. * @returns The absolute position of the bone
  81626. */
  81627. Bone.prototype.getAbsolutePosition = function (mesh) {
  81628. if (mesh === void 0) { mesh = null; }
  81629. var pos = BABYLON.Vector3.Zero();
  81630. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  81631. return pos;
  81632. };
  81633. /**
  81634. * Copy the absolute position of the bone (world space) to the result param
  81635. * @param mesh The mesh that this bone is attached to
  81636. * @param result The vector3 to copy the absolute position to
  81637. */
  81638. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  81639. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  81640. };
  81641. /**
  81642. * Compute the absolute transforms of this bone and its children
  81643. */
  81644. Bone.prototype.computeAbsoluteTransforms = function () {
  81645. this._compose();
  81646. if (this._parent) {
  81647. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81648. }
  81649. else {
  81650. this._absoluteTransform.copyFrom(this._localMatrix);
  81651. var poseMatrix = this._skeleton.getPoseMatrix();
  81652. if (poseMatrix) {
  81653. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  81654. }
  81655. }
  81656. var children = this.children;
  81657. var len = children.length;
  81658. for (var i = 0; i < len; i++) {
  81659. children[i].computeAbsoluteTransforms();
  81660. }
  81661. };
  81662. /**
  81663. * Get the world direction from an axis that is in the local space of the bone
  81664. * @param localAxis The local direction that is used to compute the world direction
  81665. * @param mesh The mesh that this bone is attached to
  81666. * @returns The world direction
  81667. */
  81668. Bone.prototype.getDirection = function (localAxis, mesh) {
  81669. if (mesh === void 0) { mesh = null; }
  81670. var result = BABYLON.Vector3.Zero();
  81671. this.getDirectionToRef(localAxis, mesh, result);
  81672. return result;
  81673. };
  81674. /**
  81675. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  81676. * @param localAxis The local direction that is used to compute the world direction
  81677. * @param mesh The mesh that this bone is attached to
  81678. * @param result The vector3 that the world direction will be copied to
  81679. */
  81680. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  81681. if (mesh === void 0) { mesh = null; }
  81682. var wm = null;
  81683. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81684. if (mesh) {
  81685. wm = mesh.getWorldMatrix();
  81686. }
  81687. this._skeleton.computeAbsoluteTransforms();
  81688. var mat = Bone._tmpMats[0];
  81689. mat.copyFrom(this.getAbsoluteTransform());
  81690. if (mesh && wm) {
  81691. mat.multiplyToRef(wm, mat);
  81692. }
  81693. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  81694. result.normalize();
  81695. };
  81696. /**
  81697. * Get the euler rotation of the bone in local or world space
  81698. * @param space The space that the rotation should be in
  81699. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81700. * @returns The euler rotation
  81701. */
  81702. Bone.prototype.getRotation = function (space, mesh) {
  81703. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81704. if (mesh === void 0) { mesh = null; }
  81705. var result = BABYLON.Vector3.Zero();
  81706. this.getRotationToRef(space, mesh, result);
  81707. return result;
  81708. };
  81709. /**
  81710. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  81711. * @param space The space that the rotation should be in
  81712. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81713. * @param result The vector3 that the rotation should be copied to
  81714. */
  81715. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  81716. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81717. if (mesh === void 0) { mesh = null; }
  81718. var quat = Bone._tmpQuat;
  81719. this.getRotationQuaternionToRef(space, mesh, quat);
  81720. quat.toEulerAnglesToRef(result);
  81721. };
  81722. /**
  81723. * Get the quaternion rotation of the bone in either local or world space
  81724. * @param space The space that the rotation should be in
  81725. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81726. * @returns The quaternion rotation
  81727. */
  81728. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  81729. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81730. if (mesh === void 0) { mesh = null; }
  81731. var result = BABYLON.Quaternion.Identity();
  81732. this.getRotationQuaternionToRef(space, mesh, result);
  81733. return result;
  81734. };
  81735. /**
  81736. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  81737. * @param space The space that the rotation should be in
  81738. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81739. * @param result The quaternion that the rotation should be copied to
  81740. */
  81741. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  81742. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81743. if (mesh === void 0) { mesh = null; }
  81744. if (space == BABYLON.Space.LOCAL) {
  81745. this._decompose();
  81746. result.copyFrom(this._localRotation);
  81747. }
  81748. else {
  81749. var mat = Bone._tmpMats[0];
  81750. var amat = this.getAbsoluteTransform();
  81751. if (mesh) {
  81752. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81753. }
  81754. else {
  81755. mat.copyFrom(amat);
  81756. }
  81757. mat.m[0] *= this._scalingDeterminant;
  81758. mat.m[1] *= this._scalingDeterminant;
  81759. mat.m[2] *= this._scalingDeterminant;
  81760. mat.decompose(undefined, result, undefined);
  81761. }
  81762. };
  81763. /**
  81764. * Get the rotation matrix of the bone in local or world space
  81765. * @param space The space that the rotation should be in
  81766. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81767. * @returns The rotation matrix
  81768. */
  81769. Bone.prototype.getRotationMatrix = function (space, mesh) {
  81770. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81771. var result = BABYLON.Matrix.Identity();
  81772. this.getRotationMatrixToRef(space, mesh, result);
  81773. return result;
  81774. };
  81775. /**
  81776. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  81777. * @param space The space that the rotation should be in
  81778. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81779. * @param result The quaternion that the rotation should be copied to
  81780. */
  81781. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  81782. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81783. if (space == BABYLON.Space.LOCAL) {
  81784. this.getLocalMatrix().getRotationMatrixToRef(result);
  81785. }
  81786. else {
  81787. var mat = Bone._tmpMats[0];
  81788. var amat = this.getAbsoluteTransform();
  81789. if (mesh) {
  81790. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81791. }
  81792. else {
  81793. mat.copyFrom(amat);
  81794. }
  81795. mat.m[0] *= this._scalingDeterminant;
  81796. mat.m[1] *= this._scalingDeterminant;
  81797. mat.m[2] *= this._scalingDeterminant;
  81798. mat.getRotationMatrixToRef(result);
  81799. }
  81800. };
  81801. /**
  81802. * Get the world position of a point that is in the local space of the bone
  81803. * @param position The local position
  81804. * @param mesh The mesh that this bone is attached to
  81805. * @returns The world position
  81806. */
  81807. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  81808. if (mesh === void 0) { mesh = null; }
  81809. var result = BABYLON.Vector3.Zero();
  81810. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  81811. return result;
  81812. };
  81813. /**
  81814. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  81815. * @param position The local position
  81816. * @param mesh The mesh that this bone is attached to
  81817. * @param result The vector3 that the world position should be copied to
  81818. */
  81819. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  81820. if (mesh === void 0) { mesh = null; }
  81821. var wm = null;
  81822. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81823. if (mesh) {
  81824. wm = mesh.getWorldMatrix();
  81825. }
  81826. this._skeleton.computeAbsoluteTransforms();
  81827. var tmat = Bone._tmpMats[0];
  81828. if (mesh && wm) {
  81829. tmat.copyFrom(this.getAbsoluteTransform());
  81830. tmat.multiplyToRef(wm, tmat);
  81831. }
  81832. else {
  81833. tmat = this.getAbsoluteTransform();
  81834. }
  81835. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81836. };
  81837. /**
  81838. * Get the local position of a point that is in world space
  81839. * @param position The world position
  81840. * @param mesh The mesh that this bone is attached to
  81841. * @returns The local position
  81842. */
  81843. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  81844. if (mesh === void 0) { mesh = null; }
  81845. var result = BABYLON.Vector3.Zero();
  81846. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  81847. return result;
  81848. };
  81849. /**
  81850. * Get the local position of a point that is in world space and copy it to the result param
  81851. * @param position The world position
  81852. * @param mesh The mesh that this bone is attached to
  81853. * @param result The vector3 that the local position should be copied to
  81854. */
  81855. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  81856. if (mesh === void 0) { mesh = null; }
  81857. var wm = null;
  81858. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81859. if (mesh) {
  81860. wm = mesh.getWorldMatrix();
  81861. }
  81862. this._skeleton.computeAbsoluteTransforms();
  81863. var tmat = Bone._tmpMats[0];
  81864. tmat.copyFrom(this.getAbsoluteTransform());
  81865. if (mesh && wm) {
  81866. tmat.multiplyToRef(wm, tmat);
  81867. }
  81868. tmat.invert();
  81869. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81870. };
  81871. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81872. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  81873. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81874. return Bone;
  81875. }(BABYLON.Node));
  81876. BABYLON.Bone = Bone;
  81877. })(BABYLON || (BABYLON = {}));
  81878. //# sourceMappingURL=babylon.bone.js.map
  81879. var BABYLON;
  81880. (function (BABYLON) {
  81881. /**
  81882. * Class used to apply inverse kinematics to bones
  81883. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  81884. */
  81885. var BoneIKController = /** @class */ (function () {
  81886. /**
  81887. * Creates a new BoneIKController
  81888. * @param mesh defines the mesh to control
  81889. * @param bone defines the bone to control
  81890. * @param options defines options to set up the controller
  81891. */
  81892. function BoneIKController(mesh, bone, options) {
  81893. /**
  81894. * Gets or sets the target position
  81895. */
  81896. this.targetPosition = BABYLON.Vector3.Zero();
  81897. /**
  81898. * Gets or sets the pole target position
  81899. */
  81900. this.poleTargetPosition = BABYLON.Vector3.Zero();
  81901. /**
  81902. * Gets or sets the pole target local offset
  81903. */
  81904. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  81905. /**
  81906. * Gets or sets the pole angle
  81907. */
  81908. this.poleAngle = 0;
  81909. /**
  81910. * 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)
  81911. */
  81912. this.slerpAmount = 1;
  81913. this._bone1Quat = BABYLON.Quaternion.Identity();
  81914. this._bone1Mat = BABYLON.Matrix.Identity();
  81915. this._bone2Ang = Math.PI;
  81916. this._maxAngle = Math.PI;
  81917. this._rightHandedSystem = false;
  81918. this._bendAxis = BABYLON.Vector3.Right();
  81919. this._slerping = false;
  81920. this._adjustRoll = 0;
  81921. this._bone2 = bone;
  81922. this._bone1 = bone.getParent();
  81923. if (!this._bone1) {
  81924. return;
  81925. }
  81926. this.mesh = mesh;
  81927. var bonePos = bone.getPosition();
  81928. if (bone.getAbsoluteTransform().determinant() > 0) {
  81929. this._rightHandedSystem = true;
  81930. this._bendAxis.x = 0;
  81931. this._bendAxis.y = 0;
  81932. this._bendAxis.z = -1;
  81933. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  81934. this._adjustRoll = Math.PI * .5;
  81935. this._bendAxis.z = 1;
  81936. }
  81937. }
  81938. if (this._bone1.length) {
  81939. var boneScale1 = this._bone1.getScale();
  81940. var boneScale2 = this._bone2.getScale();
  81941. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  81942. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  81943. }
  81944. else if (this._bone1.children[0]) {
  81945. mesh.computeWorldMatrix(true);
  81946. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  81947. var pos2 = this._bone2.getAbsolutePosition(mesh);
  81948. var pos3 = this._bone1.getAbsolutePosition(mesh);
  81949. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  81950. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  81951. }
  81952. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  81953. this.maxAngle = Math.PI;
  81954. if (options) {
  81955. if (options.targetMesh) {
  81956. this.targetMesh = options.targetMesh;
  81957. this.targetMesh.computeWorldMatrix(true);
  81958. }
  81959. if (options.poleTargetMesh) {
  81960. this.poleTargetMesh = options.poleTargetMesh;
  81961. this.poleTargetMesh.computeWorldMatrix(true);
  81962. }
  81963. else if (options.poleTargetBone) {
  81964. this.poleTargetBone = options.poleTargetBone;
  81965. }
  81966. else if (this._bone1.getParent()) {
  81967. this.poleTargetBone = this._bone1.getParent();
  81968. }
  81969. if (options.poleTargetLocalOffset) {
  81970. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  81971. }
  81972. if (options.poleAngle) {
  81973. this.poleAngle = options.poleAngle;
  81974. }
  81975. if (options.bendAxis) {
  81976. this._bendAxis.copyFrom(options.bendAxis);
  81977. }
  81978. if (options.maxAngle) {
  81979. this.maxAngle = options.maxAngle;
  81980. }
  81981. if (options.slerpAmount) {
  81982. this.slerpAmount = options.slerpAmount;
  81983. }
  81984. }
  81985. }
  81986. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  81987. /**
  81988. * Gets or sets maximum allowed angle
  81989. */
  81990. get: function () {
  81991. return this._maxAngle;
  81992. },
  81993. set: function (value) {
  81994. this._setMaxAngle(value);
  81995. },
  81996. enumerable: true,
  81997. configurable: true
  81998. });
  81999. BoneIKController.prototype._setMaxAngle = function (ang) {
  82000. if (ang < 0) {
  82001. ang = 0;
  82002. }
  82003. if (ang > Math.PI || ang == undefined) {
  82004. ang = Math.PI;
  82005. }
  82006. this._maxAngle = ang;
  82007. var a = this._bone1Length;
  82008. var b = this._bone2Length;
  82009. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  82010. };
  82011. /**
  82012. * Force the controller to update the bones
  82013. */
  82014. BoneIKController.prototype.update = function () {
  82015. var bone1 = this._bone1;
  82016. if (!bone1) {
  82017. return;
  82018. }
  82019. var target = this.targetPosition;
  82020. var poleTarget = this.poleTargetPosition;
  82021. var mat1 = BoneIKController._tmpMats[0];
  82022. var mat2 = BoneIKController._tmpMats[1];
  82023. if (this.targetMesh) {
  82024. target.copyFrom(this.targetMesh.getAbsolutePosition());
  82025. }
  82026. if (this.poleTargetBone) {
  82027. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  82028. }
  82029. else if (this.poleTargetMesh) {
  82030. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  82031. }
  82032. var bonePos = BoneIKController._tmpVecs[0];
  82033. var zaxis = BoneIKController._tmpVecs[1];
  82034. var xaxis = BoneIKController._tmpVecs[2];
  82035. var yaxis = BoneIKController._tmpVecs[3];
  82036. var upAxis = BoneIKController._tmpVecs[4];
  82037. var _tmpQuat = BoneIKController._tmpQuat;
  82038. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  82039. poleTarget.subtractToRef(bonePos, upAxis);
  82040. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  82041. upAxis.y = 1;
  82042. }
  82043. else {
  82044. upAxis.normalize();
  82045. }
  82046. target.subtractToRef(bonePos, yaxis);
  82047. yaxis.normalize();
  82048. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  82049. zaxis.normalize();
  82050. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  82051. xaxis.normalize();
  82052. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  82053. var a = this._bone1Length;
  82054. var b = this._bone2Length;
  82055. var c = BABYLON.Vector3.Distance(bonePos, target);
  82056. if (this._maxReach > 0) {
  82057. c = Math.min(this._maxReach, c);
  82058. }
  82059. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  82060. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  82061. if (acosa > 1) {
  82062. acosa = 1;
  82063. }
  82064. if (acosb > 1) {
  82065. acosb = 1;
  82066. }
  82067. if (acosa < -1) {
  82068. acosa = -1;
  82069. }
  82070. if (acosb < -1) {
  82071. acosb = -1;
  82072. }
  82073. var angA = Math.acos(acosa);
  82074. var angB = Math.acos(acosb);
  82075. var angC = -angA - angB;
  82076. if (this._rightHandedSystem) {
  82077. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  82078. mat2.multiplyToRef(mat1, mat1);
  82079. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  82080. mat2.multiplyToRef(mat1, mat1);
  82081. }
  82082. else {
  82083. var _tmpVec = BoneIKController._tmpVecs[5];
  82084. _tmpVec.copyFrom(this._bendAxis);
  82085. _tmpVec.x *= -1;
  82086. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  82087. mat2.multiplyToRef(mat1, mat1);
  82088. }
  82089. if (this.poleAngle) {
  82090. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  82091. mat1.multiplyToRef(mat2, mat1);
  82092. }
  82093. if (this._bone1) {
  82094. if (this.slerpAmount < 1) {
  82095. if (!this._slerping) {
  82096. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  82097. }
  82098. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  82099. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  82100. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  82101. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  82102. this._slerping = true;
  82103. }
  82104. else {
  82105. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  82106. this._bone1Mat.copyFrom(mat1);
  82107. this._slerping = false;
  82108. }
  82109. }
  82110. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  82111. this._bone2Ang = angC;
  82112. };
  82113. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82114. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  82115. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82116. return BoneIKController;
  82117. }());
  82118. BABYLON.BoneIKController = BoneIKController;
  82119. })(BABYLON || (BABYLON = {}));
  82120. //# sourceMappingURL=babylon.boneIKController.js.map
  82121. var BABYLON;
  82122. (function (BABYLON) {
  82123. /**
  82124. * Class used to make a bone look toward a point in space
  82125. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  82126. */
  82127. var BoneLookController = /** @class */ (function () {
  82128. /**
  82129. * Create a BoneLookController
  82130. * @param mesh the mesh that the bone belongs to
  82131. * @param bone the bone that will be looking to the target
  82132. * @param target the target Vector3 to look at
  82133. * @param settings optional settings:
  82134. * * maxYaw: the maximum angle the bone will yaw to
  82135. * * minYaw: the minimum angle the bone will yaw to
  82136. * * maxPitch: the maximum angle the bone will pitch to
  82137. * * minPitch: the minimum angle the bone will yaw to
  82138. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  82139. * * upAxis: the up axis of the coordinate system
  82140. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  82141. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  82142. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  82143. * * adjustYaw: used to make an adjustment to the yaw of the bone
  82144. * * adjustPitch: used to make an adjustment to the pitch of the bone
  82145. * * adjustRoll: used to make an adjustment to the roll of the bone
  82146. **/
  82147. function BoneLookController(mesh, bone, target, options) {
  82148. /**
  82149. * The up axis of the coordinate system that is used when the bone is rotated
  82150. */
  82151. this.upAxis = BABYLON.Vector3.Up();
  82152. /**
  82153. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  82154. */
  82155. this.upAxisSpace = BABYLON.Space.LOCAL;
  82156. /**
  82157. * Used to make an adjustment to the yaw of the bone
  82158. */
  82159. this.adjustYaw = 0;
  82160. /**
  82161. * Used to make an adjustment to the pitch of the bone
  82162. */
  82163. this.adjustPitch = 0;
  82164. /**
  82165. * Used to make an adjustment to the roll of the bone
  82166. */
  82167. this.adjustRoll = 0;
  82168. /**
  82169. * 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)
  82170. */
  82171. this.slerpAmount = 1;
  82172. this._boneQuat = BABYLON.Quaternion.Identity();
  82173. this._slerping = false;
  82174. this._firstFrameSkipped = false;
  82175. this._fowardAxis = BABYLON.Vector3.Forward();
  82176. this.mesh = mesh;
  82177. this.bone = bone;
  82178. this.target = target;
  82179. if (options) {
  82180. if (options.adjustYaw) {
  82181. this.adjustYaw = options.adjustYaw;
  82182. }
  82183. if (options.adjustPitch) {
  82184. this.adjustPitch = options.adjustPitch;
  82185. }
  82186. if (options.adjustRoll) {
  82187. this.adjustRoll = options.adjustRoll;
  82188. }
  82189. if (options.maxYaw != null) {
  82190. this.maxYaw = options.maxYaw;
  82191. }
  82192. else {
  82193. this.maxYaw = Math.PI;
  82194. }
  82195. if (options.minYaw != null) {
  82196. this.minYaw = options.minYaw;
  82197. }
  82198. else {
  82199. this.minYaw = -Math.PI;
  82200. }
  82201. if (options.maxPitch != null) {
  82202. this.maxPitch = options.maxPitch;
  82203. }
  82204. else {
  82205. this.maxPitch = Math.PI;
  82206. }
  82207. if (options.minPitch != null) {
  82208. this.minPitch = options.minPitch;
  82209. }
  82210. else {
  82211. this.minPitch = -Math.PI;
  82212. }
  82213. if (options.slerpAmount != null) {
  82214. this.slerpAmount = options.slerpAmount;
  82215. }
  82216. if (options.upAxis != null) {
  82217. this.upAxis = options.upAxis;
  82218. }
  82219. if (options.upAxisSpace != null) {
  82220. this.upAxisSpace = options.upAxisSpace;
  82221. }
  82222. if (options.yawAxis != null || options.pitchAxis != null) {
  82223. var newYawAxis = BABYLON.Axis.Y;
  82224. var newPitchAxis = BABYLON.Axis.X;
  82225. if (options.yawAxis != null) {
  82226. newYawAxis = options.yawAxis.clone();
  82227. newYawAxis.normalize();
  82228. }
  82229. if (options.pitchAxis != null) {
  82230. newPitchAxis = options.pitchAxis.clone();
  82231. newPitchAxis.normalize();
  82232. }
  82233. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  82234. this._transformYawPitch = BABYLON.Matrix.Identity();
  82235. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  82236. this._transformYawPitchInv = this._transformYawPitch.clone();
  82237. this._transformYawPitch.invert();
  82238. }
  82239. }
  82240. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  82241. this.upAxisSpace = BABYLON.Space.LOCAL;
  82242. }
  82243. }
  82244. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  82245. /**
  82246. * Gets or sets the minimum yaw angle that the bone can look to
  82247. */
  82248. get: function () {
  82249. return this._minYaw;
  82250. },
  82251. set: function (value) {
  82252. this._minYaw = value;
  82253. this._minYawSin = Math.sin(value);
  82254. this._minYawCos = Math.cos(value);
  82255. if (this._maxYaw != null) {
  82256. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82257. this._yawRange = this._maxYaw - this._minYaw;
  82258. }
  82259. },
  82260. enumerable: true,
  82261. configurable: true
  82262. });
  82263. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  82264. /**
  82265. * Gets or sets the maximum yaw angle that the bone can look to
  82266. */
  82267. get: function () {
  82268. return this._maxYaw;
  82269. },
  82270. set: function (value) {
  82271. this._maxYaw = value;
  82272. this._maxYawSin = Math.sin(value);
  82273. this._maxYawCos = Math.cos(value);
  82274. if (this._minYaw != null) {
  82275. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82276. this._yawRange = this._maxYaw - this._minYaw;
  82277. }
  82278. },
  82279. enumerable: true,
  82280. configurable: true
  82281. });
  82282. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  82283. /**
  82284. * Gets or sets the minimum pitch angle that the bone can look to
  82285. */
  82286. get: function () {
  82287. return this._minPitch;
  82288. },
  82289. set: function (value) {
  82290. this._minPitch = value;
  82291. this._minPitchTan = Math.tan(value);
  82292. },
  82293. enumerable: true,
  82294. configurable: true
  82295. });
  82296. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  82297. /**
  82298. * Gets or sets the maximum pitch angle that the bone can look to
  82299. */
  82300. get: function () {
  82301. return this._maxPitch;
  82302. },
  82303. set: function (value) {
  82304. this._maxPitch = value;
  82305. this._maxPitchTan = Math.tan(value);
  82306. },
  82307. enumerable: true,
  82308. configurable: true
  82309. });
  82310. /**
  82311. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  82312. */
  82313. BoneLookController.prototype.update = function () {
  82314. //skip the first frame when slerping so that the mesh rotation is correct
  82315. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  82316. this._firstFrameSkipped = true;
  82317. return;
  82318. }
  82319. var bone = this.bone;
  82320. var bonePos = BoneLookController._tmpVecs[0];
  82321. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  82322. var target = this.target;
  82323. var _tmpMat1 = BoneLookController._tmpMats[0];
  82324. var _tmpMat2 = BoneLookController._tmpMats[1];
  82325. var mesh = this.mesh;
  82326. var parentBone = bone.getParent();
  82327. var upAxis = BoneLookController._tmpVecs[1];
  82328. upAxis.copyFrom(this.upAxis);
  82329. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  82330. if (this._transformYawPitch) {
  82331. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  82332. }
  82333. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  82334. }
  82335. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  82336. mesh.getDirectionToRef(upAxis, upAxis);
  82337. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  82338. upAxis.normalize();
  82339. }
  82340. }
  82341. var checkYaw = false;
  82342. var checkPitch = false;
  82343. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  82344. checkYaw = true;
  82345. }
  82346. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  82347. checkPitch = true;
  82348. }
  82349. if (checkYaw || checkPitch) {
  82350. var spaceMat = BoneLookController._tmpMats[2];
  82351. var spaceMatInv = BoneLookController._tmpMats[3];
  82352. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  82353. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  82354. }
  82355. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  82356. spaceMat.copyFrom(mesh.getWorldMatrix());
  82357. }
  82358. else {
  82359. var forwardAxis = BoneLookController._tmpVecs[2];
  82360. forwardAxis.copyFrom(this._fowardAxis);
  82361. if (this._transformYawPitch) {
  82362. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  82363. }
  82364. if (parentBone) {
  82365. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  82366. }
  82367. else {
  82368. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  82369. }
  82370. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  82371. rightAxis.normalize();
  82372. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  82373. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  82374. }
  82375. spaceMat.invertToRef(spaceMatInv);
  82376. var xzlen = null;
  82377. if (checkPitch) {
  82378. var localTarget = BoneLookController._tmpVecs[3];
  82379. target.subtractToRef(bonePos, localTarget);
  82380. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82381. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82382. var pitch = Math.atan2(localTarget.y, xzlen);
  82383. var newPitch = pitch;
  82384. if (pitch > this._maxPitch) {
  82385. localTarget.y = this._maxPitchTan * xzlen;
  82386. newPitch = this._maxPitch;
  82387. }
  82388. else if (pitch < this._minPitch) {
  82389. localTarget.y = this._minPitchTan * xzlen;
  82390. newPitch = this._minPitch;
  82391. }
  82392. if (pitch != newPitch) {
  82393. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82394. localTarget.addInPlace(bonePos);
  82395. target = localTarget;
  82396. }
  82397. }
  82398. if (checkYaw) {
  82399. var localTarget = BoneLookController._tmpVecs[4];
  82400. target.subtractToRef(bonePos, localTarget);
  82401. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82402. var yaw = Math.atan2(localTarget.x, localTarget.z);
  82403. var newYaw = yaw;
  82404. if (yaw > this._maxYaw || yaw < this._minYaw) {
  82405. if (xzlen == null) {
  82406. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82407. }
  82408. if (this._yawRange > Math.PI) {
  82409. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  82410. localTarget.z = this._maxYawCos * xzlen;
  82411. localTarget.x = this._maxYawSin * xzlen;
  82412. newYaw = this._maxYaw;
  82413. }
  82414. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  82415. localTarget.z = this._minYawCos * xzlen;
  82416. localTarget.x = this._minYawSin * xzlen;
  82417. newYaw = this._minYaw;
  82418. }
  82419. }
  82420. else {
  82421. if (yaw > this._maxYaw) {
  82422. localTarget.z = this._maxYawCos * xzlen;
  82423. localTarget.x = this._maxYawSin * xzlen;
  82424. newYaw = this._maxYaw;
  82425. }
  82426. else if (yaw < this._minYaw) {
  82427. localTarget.z = this._minYawCos * xzlen;
  82428. localTarget.x = this._minYawSin * xzlen;
  82429. newYaw = this._minYaw;
  82430. }
  82431. }
  82432. }
  82433. if (this._slerping && this._yawRange > Math.PI) {
  82434. //are we going to be crossing into the min/max region?
  82435. var boneFwd = BoneLookController._tmpVecs[8];
  82436. boneFwd.copyFrom(BABYLON.Axis.Z);
  82437. if (this._transformYawPitch) {
  82438. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  82439. }
  82440. var boneRotMat = BoneLookController._tmpMats[4];
  82441. this._boneQuat.toRotationMatrix(boneRotMat);
  82442. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  82443. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  82444. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  82445. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  82446. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  82447. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  82448. if (angBtwTar > angBtwMidYaw) {
  82449. if (xzlen == null) {
  82450. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82451. }
  82452. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  82453. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  82454. if (angBtwMin < angBtwMax) {
  82455. newYaw = boneYaw + Math.PI * .75;
  82456. localTarget.z = Math.cos(newYaw) * xzlen;
  82457. localTarget.x = Math.sin(newYaw) * xzlen;
  82458. }
  82459. else {
  82460. newYaw = boneYaw - Math.PI * .75;
  82461. localTarget.z = Math.cos(newYaw) * xzlen;
  82462. localTarget.x = Math.sin(newYaw) * xzlen;
  82463. }
  82464. }
  82465. }
  82466. if (yaw != newYaw) {
  82467. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82468. localTarget.addInPlace(bonePos);
  82469. target = localTarget;
  82470. }
  82471. }
  82472. }
  82473. var zaxis = BoneLookController._tmpVecs[5];
  82474. var xaxis = BoneLookController._tmpVecs[6];
  82475. var yaxis = BoneLookController._tmpVecs[7];
  82476. var _tmpQuat = BoneLookController._tmpQuat;
  82477. target.subtractToRef(bonePos, zaxis);
  82478. zaxis.normalize();
  82479. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  82480. xaxis.normalize();
  82481. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  82482. yaxis.normalize();
  82483. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  82484. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  82485. return;
  82486. }
  82487. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  82488. return;
  82489. }
  82490. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  82491. return;
  82492. }
  82493. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  82494. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  82495. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  82496. }
  82497. if (this.slerpAmount < 1) {
  82498. if (!this._slerping) {
  82499. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  82500. }
  82501. if (this._transformYawPitch) {
  82502. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82503. }
  82504. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  82505. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  82506. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  82507. this._slerping = true;
  82508. }
  82509. else {
  82510. if (this._transformYawPitch) {
  82511. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82512. }
  82513. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  82514. this._slerping = false;
  82515. }
  82516. };
  82517. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  82518. var angDiff = ang2 - ang1;
  82519. angDiff %= Math.PI * 2;
  82520. if (angDiff > Math.PI) {
  82521. angDiff -= Math.PI * 2;
  82522. }
  82523. else if (angDiff < -Math.PI) {
  82524. angDiff += Math.PI * 2;
  82525. }
  82526. return angDiff;
  82527. };
  82528. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  82529. ang1 %= (2 * Math.PI);
  82530. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82531. ang2 %= (2 * Math.PI);
  82532. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82533. var ab = 0;
  82534. if (ang1 < ang2) {
  82535. ab = ang2 - ang1;
  82536. }
  82537. else {
  82538. ab = ang1 - ang2;
  82539. }
  82540. if (ab > Math.PI) {
  82541. ab = Math.PI * 2 - ab;
  82542. }
  82543. return ab;
  82544. };
  82545. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  82546. ang %= (2 * Math.PI);
  82547. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  82548. ang1 %= (2 * Math.PI);
  82549. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82550. ang2 %= (2 * Math.PI);
  82551. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82552. if (ang1 < ang2) {
  82553. if (ang > ang1 && ang < ang2) {
  82554. return true;
  82555. }
  82556. }
  82557. else {
  82558. if (ang > ang2 && ang < ang1) {
  82559. return true;
  82560. }
  82561. }
  82562. return false;
  82563. };
  82564. 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()];
  82565. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  82566. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82567. return BoneLookController;
  82568. }());
  82569. BABYLON.BoneLookController = BoneLookController;
  82570. })(BABYLON || (BABYLON = {}));
  82571. //# sourceMappingURL=babylon.boneLookController.js.map
  82572. var BABYLON;
  82573. (function (BABYLON) {
  82574. /**
  82575. * Class used to handle skinning animations
  82576. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82577. */
  82578. var Skeleton = /** @class */ (function () {
  82579. /**
  82580. * Creates a new skeleton
  82581. * @param name defines the skeleton name
  82582. * @param id defines the skeleton Id
  82583. * @param scene defines the hosting scene
  82584. */
  82585. function Skeleton(
  82586. /** defines the skeleton name */
  82587. name,
  82588. /** defines the skeleton Id */
  82589. id, scene) {
  82590. this.name = name;
  82591. this.id = id;
  82592. /**
  82593. * Gets the list of child bones
  82594. */
  82595. this.bones = new Array();
  82596. /**
  82597. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  82598. */
  82599. this.needInitialSkinMatrix = false;
  82600. this._isDirty = true;
  82601. this._meshesWithPoseMatrix = new Array();
  82602. this._identity = BABYLON.Matrix.Identity();
  82603. this._ranges = {};
  82604. this._lastAbsoluteTransformsUpdateId = -1;
  82605. /**
  82606. * Specifies if the skeleton should be serialized
  82607. */
  82608. this.doNotSerialize = false;
  82609. this._animationPropertiesOverride = null;
  82610. // Events
  82611. /**
  82612. * An observable triggered before computing the skeleton's matrices
  82613. */
  82614. this.onBeforeComputeObservable = new BABYLON.Observable();
  82615. this.bones = [];
  82616. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82617. scene.skeletons.push(this);
  82618. //make sure it will recalculate the matrix next time prepare is called.
  82619. this._isDirty = true;
  82620. }
  82621. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  82622. /**
  82623. * Gets or sets the animation properties override
  82624. */
  82625. get: function () {
  82626. if (!this._animationPropertiesOverride) {
  82627. return this._scene.animationPropertiesOverride;
  82628. }
  82629. return this._animationPropertiesOverride;
  82630. },
  82631. set: function (value) {
  82632. this._animationPropertiesOverride = value;
  82633. },
  82634. enumerable: true,
  82635. configurable: true
  82636. });
  82637. // Members
  82638. /**
  82639. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  82640. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  82641. * @returns a Float32Array containing matrices data
  82642. */
  82643. Skeleton.prototype.getTransformMatrices = function (mesh) {
  82644. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  82645. return mesh._bonesTransformMatrices;
  82646. }
  82647. if (!this._transformMatrices) {
  82648. this.prepare();
  82649. }
  82650. return this._transformMatrices;
  82651. };
  82652. /**
  82653. * Gets the current hosting scene
  82654. * @returns a scene object
  82655. */
  82656. Skeleton.prototype.getScene = function () {
  82657. return this._scene;
  82658. };
  82659. // Methods
  82660. /**
  82661. * Gets a string representing the current skeleton data
  82662. * @param fullDetails defines a boolean indicating if we want a verbose version
  82663. * @returns a string representing the current skeleton data
  82664. */
  82665. Skeleton.prototype.toString = function (fullDetails) {
  82666. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  82667. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  82668. if (fullDetails) {
  82669. ret += ", Ranges: {";
  82670. var first = true;
  82671. for (var name_1 in this._ranges) {
  82672. if (first) {
  82673. ret += ", ";
  82674. first = false;
  82675. }
  82676. ret += name_1;
  82677. }
  82678. ret += "}";
  82679. }
  82680. return ret;
  82681. };
  82682. /**
  82683. * Get bone's index searching by name
  82684. * @param name defines bone's name to search for
  82685. * @return the indice of the bone. Returns -1 if not found
  82686. */
  82687. Skeleton.prototype.getBoneIndexByName = function (name) {
  82688. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  82689. if (this.bones[boneIndex].name === name) {
  82690. return boneIndex;
  82691. }
  82692. }
  82693. return -1;
  82694. };
  82695. /**
  82696. * Creater a new animation range
  82697. * @param name defines the name of the range
  82698. * @param from defines the start key
  82699. * @param to defines the end key
  82700. */
  82701. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  82702. // check name not already in use
  82703. if (!this._ranges[name]) {
  82704. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  82705. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82706. if (this.bones[i].animations[0]) {
  82707. this.bones[i].animations[0].createRange(name, from, to);
  82708. }
  82709. }
  82710. }
  82711. };
  82712. /**
  82713. * Delete a specific animation range
  82714. * @param name defines the name of the range
  82715. * @param deleteFrames defines if frames must be removed as well
  82716. */
  82717. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  82718. if (deleteFrames === void 0) { deleteFrames = true; }
  82719. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82720. if (this.bones[i].animations[0]) {
  82721. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  82722. }
  82723. }
  82724. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  82725. };
  82726. /**
  82727. * Gets a specific animation range
  82728. * @param name defines the name of the range to look for
  82729. * @returns the requested animation range or null if not found
  82730. */
  82731. Skeleton.prototype.getAnimationRange = function (name) {
  82732. return this._ranges[name];
  82733. };
  82734. /**
  82735. * Gets the list of all animation ranges defined on this skeleton
  82736. * @returns an array
  82737. */
  82738. Skeleton.prototype.getAnimationRanges = function () {
  82739. var animationRanges = [];
  82740. var name;
  82741. var i = 0;
  82742. for (name in this._ranges) {
  82743. animationRanges[i] = this._ranges[name];
  82744. i++;
  82745. }
  82746. return animationRanges;
  82747. };
  82748. /**
  82749. * Copy animation range from a source skeleton.
  82750. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  82751. * @param source defines the source skeleton
  82752. * @param name defines the name of the range to copy
  82753. * @param rescaleAsRequired defines if rescaling must be applied if required
  82754. * @returns true if operation was successful
  82755. */
  82756. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  82757. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82758. if (this._ranges[name] || !source.getAnimationRange(name)) {
  82759. return false;
  82760. }
  82761. var ret = true;
  82762. var frameOffset = this._getHighestAnimationFrame() + 1;
  82763. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  82764. var boneDict = {};
  82765. var sourceBones = source.bones;
  82766. var nBones;
  82767. var i;
  82768. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  82769. boneDict[sourceBones[i].name] = sourceBones[i];
  82770. }
  82771. if (this.bones.length !== sourceBones.length) {
  82772. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  82773. ret = false;
  82774. }
  82775. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  82776. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  82777. var boneName = this.bones[i].name;
  82778. var sourceBone = boneDict[boneName];
  82779. if (sourceBone) {
  82780. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  82781. }
  82782. else {
  82783. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  82784. ret = false;
  82785. }
  82786. }
  82787. // do not call createAnimationRange(), since it also is done to bones, which was already done
  82788. var range = source.getAnimationRange(name);
  82789. if (range) {
  82790. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  82791. }
  82792. return ret;
  82793. };
  82794. /**
  82795. * Forces the skeleton to go to rest pose
  82796. */
  82797. Skeleton.prototype.returnToRest = function () {
  82798. for (var index = 0; index < this.bones.length; index++) {
  82799. this.bones[index].returnToRest();
  82800. }
  82801. };
  82802. Skeleton.prototype._getHighestAnimationFrame = function () {
  82803. var ret = 0;
  82804. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82805. if (this.bones[i].animations[0]) {
  82806. var highest = this.bones[i].animations[0].getHighestFrame();
  82807. if (ret < highest) {
  82808. ret = highest;
  82809. }
  82810. }
  82811. }
  82812. return ret;
  82813. };
  82814. /**
  82815. * Begin a specific animation range
  82816. * @param name defines the name of the range to start
  82817. * @param loop defines if looping must be turned on (false by default)
  82818. * @param speedRatio defines the speed ratio to apply (1 by default)
  82819. * @param onAnimationEnd defines a callback which will be called when animation will end
  82820. * @returns a new animatable
  82821. */
  82822. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  82823. var range = this.getAnimationRange(name);
  82824. if (!range) {
  82825. return null;
  82826. }
  82827. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  82828. };
  82829. /** @hidden */
  82830. Skeleton.prototype._markAsDirty = function () {
  82831. this._isDirty = true;
  82832. };
  82833. /** @hidden */
  82834. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  82835. this._meshesWithPoseMatrix.push(mesh);
  82836. };
  82837. /** @hidden */
  82838. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  82839. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  82840. if (index > -1) {
  82841. this._meshesWithPoseMatrix.splice(index, 1);
  82842. }
  82843. };
  82844. /** @hidden */
  82845. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  82846. this.onBeforeComputeObservable.notifyObservers(this);
  82847. for (var index = 0; index < this.bones.length; index++) {
  82848. var bone = this.bones[index];
  82849. var parentBone = bone.getParent();
  82850. if (parentBone) {
  82851. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  82852. }
  82853. else {
  82854. if (initialSkinMatrix) {
  82855. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  82856. }
  82857. else {
  82858. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  82859. }
  82860. }
  82861. if (bone._index !== -1) {
  82862. var mappedIndex = bone._index === null ? index : bone._index;
  82863. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  82864. }
  82865. }
  82866. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  82867. };
  82868. /**
  82869. * Build all resources required to render a skeleton
  82870. */
  82871. Skeleton.prototype.prepare = function () {
  82872. if (!this._isDirty) {
  82873. return;
  82874. }
  82875. if (this.needInitialSkinMatrix) {
  82876. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  82877. var mesh = this._meshesWithPoseMatrix[index];
  82878. var poseMatrix = mesh.getPoseMatrix();
  82879. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  82880. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82881. }
  82882. if (this._synchronizedWithMesh !== mesh) {
  82883. this._synchronizedWithMesh = mesh;
  82884. // Prepare bones
  82885. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  82886. var bone = this.bones[boneIndex];
  82887. if (!bone.getParent()) {
  82888. var matrix = bone.getBaseMatrix();
  82889. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  82890. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  82891. }
  82892. }
  82893. }
  82894. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  82895. }
  82896. }
  82897. else {
  82898. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  82899. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82900. }
  82901. this._computeTransformMatrices(this._transformMatrices, null);
  82902. }
  82903. this._isDirty = false;
  82904. this._scene._activeBones.addCount(this.bones.length, false);
  82905. };
  82906. /**
  82907. * Gets the list of animatables currently running for this skeleton
  82908. * @returns an array of animatables
  82909. */
  82910. Skeleton.prototype.getAnimatables = function () {
  82911. if (!this._animatables || this._animatables.length !== this.bones.length) {
  82912. this._animatables = [];
  82913. for (var index = 0; index < this.bones.length; index++) {
  82914. this._animatables.push(this.bones[index]);
  82915. }
  82916. }
  82917. return this._animatables;
  82918. };
  82919. /**
  82920. * Clone the current skeleton
  82921. * @param name defines the name of the new skeleton
  82922. * @param id defines the id of the enw skeleton
  82923. * @returns the new skeleton
  82924. */
  82925. Skeleton.prototype.clone = function (name, id) {
  82926. var result = new Skeleton(name, id || name, this._scene);
  82927. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82928. for (var index = 0; index < this.bones.length; index++) {
  82929. var source = this.bones[index];
  82930. var parentBone = null;
  82931. var parent_1 = source.getParent();
  82932. if (parent_1) {
  82933. var parentIndex = this.bones.indexOf(parent_1);
  82934. parentBone = result.bones[parentIndex];
  82935. }
  82936. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  82937. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  82938. }
  82939. if (this._ranges) {
  82940. result._ranges = {};
  82941. for (var rangeName in this._ranges) {
  82942. var range = this._ranges[rangeName];
  82943. if (range) {
  82944. result._ranges[rangeName] = range.clone();
  82945. }
  82946. }
  82947. }
  82948. this._isDirty = true;
  82949. return result;
  82950. };
  82951. /**
  82952. * Enable animation blending for this skeleton
  82953. * @param blendingSpeed defines the blending speed to apply
  82954. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  82955. */
  82956. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  82957. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  82958. this.bones.forEach(function (bone) {
  82959. bone.animations.forEach(function (animation) {
  82960. animation.enableBlending = true;
  82961. animation.blendingSpeed = blendingSpeed;
  82962. });
  82963. });
  82964. };
  82965. /**
  82966. * Releases all resources associated with the current skeleton
  82967. */
  82968. Skeleton.prototype.dispose = function () {
  82969. this._meshesWithPoseMatrix = [];
  82970. // Animations
  82971. this.getScene().stopAnimation(this);
  82972. // Remove from scene
  82973. this.getScene().removeSkeleton(this);
  82974. };
  82975. /**
  82976. * Serialize the skeleton in a JSON object
  82977. * @returns a JSON object
  82978. */
  82979. Skeleton.prototype.serialize = function () {
  82980. var serializationObject = {};
  82981. serializationObject.name = this.name;
  82982. serializationObject.id = this.id;
  82983. if (this.dimensionsAtRest) {
  82984. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  82985. }
  82986. serializationObject.bones = [];
  82987. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82988. for (var index = 0; index < this.bones.length; index++) {
  82989. var bone = this.bones[index];
  82990. var parent_2 = bone.getParent();
  82991. var serializedBone = {
  82992. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  82993. name: bone.name,
  82994. matrix: bone.getBaseMatrix().toArray(),
  82995. rest: bone.getRestPose().toArray()
  82996. };
  82997. serializationObject.bones.push(serializedBone);
  82998. if (bone.length) {
  82999. serializedBone.length = bone.length;
  83000. }
  83001. if (bone.metadata) {
  83002. serializedBone.metadata = bone.metadata;
  83003. }
  83004. if (bone.animations && bone.animations.length > 0) {
  83005. serializedBone.animation = bone.animations[0].serialize();
  83006. }
  83007. serializationObject.ranges = [];
  83008. for (var name in this._ranges) {
  83009. var source = this._ranges[name];
  83010. if (!source) {
  83011. continue;
  83012. }
  83013. var range = {};
  83014. range.name = name;
  83015. range.from = source.from;
  83016. range.to = source.to;
  83017. serializationObject.ranges.push(range);
  83018. }
  83019. }
  83020. return serializationObject;
  83021. };
  83022. /**
  83023. * Creates a new skeleton from serialized data
  83024. * @param parsedSkeleton defines the serialized data
  83025. * @param scene defines the hosting scene
  83026. * @returns a new skeleton
  83027. */
  83028. Skeleton.Parse = function (parsedSkeleton, scene) {
  83029. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  83030. if (parsedSkeleton.dimensionsAtRest) {
  83031. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  83032. }
  83033. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  83034. var index;
  83035. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  83036. var parsedBone = parsedSkeleton.bones[index];
  83037. var parentBone = null;
  83038. if (parsedBone.parentBoneIndex > -1) {
  83039. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  83040. }
  83041. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  83042. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  83043. if (parsedBone.length) {
  83044. bone.length = parsedBone.length;
  83045. }
  83046. if (parsedBone.metadata) {
  83047. bone.metadata = parsedBone.metadata;
  83048. }
  83049. if (parsedBone.animation) {
  83050. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  83051. }
  83052. }
  83053. // placed after bones, so createAnimationRange can cascade down
  83054. if (parsedSkeleton.ranges) {
  83055. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  83056. var data = parsedSkeleton.ranges[index];
  83057. skeleton.createAnimationRange(data.name, data.from, data.to);
  83058. }
  83059. }
  83060. return skeleton;
  83061. };
  83062. /**
  83063. * Compute all node absolute transforms
  83064. * @param forceUpdate defines if computation must be done even if cache is up to date
  83065. */
  83066. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  83067. if (forceUpdate === void 0) { forceUpdate = false; }
  83068. var renderId = this._scene.getRenderId();
  83069. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  83070. this.bones[0].computeAbsoluteTransforms();
  83071. this._lastAbsoluteTransformsUpdateId = renderId;
  83072. }
  83073. };
  83074. /**
  83075. * Gets the root pose matrix
  83076. * @returns a matrix
  83077. */
  83078. Skeleton.prototype.getPoseMatrix = function () {
  83079. var poseMatrix = null;
  83080. if (this._meshesWithPoseMatrix.length > 0) {
  83081. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  83082. }
  83083. return poseMatrix;
  83084. };
  83085. /**
  83086. * Sorts bones per internal index
  83087. */
  83088. Skeleton.prototype.sortBones = function () {
  83089. var bones = new Array();
  83090. var visited = new Array(this.bones.length);
  83091. for (var index = 0; index < this.bones.length; index++) {
  83092. this._sortBones(index, bones, visited);
  83093. }
  83094. this.bones = bones;
  83095. };
  83096. Skeleton.prototype._sortBones = function (index, bones, visited) {
  83097. if (visited[index]) {
  83098. return;
  83099. }
  83100. visited[index] = true;
  83101. var bone = this.bones[index];
  83102. if (bone._index === undefined) {
  83103. bone._index = index;
  83104. }
  83105. var parentBone = bone.getParent();
  83106. if (parentBone) {
  83107. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  83108. }
  83109. bones.push(bone);
  83110. };
  83111. return Skeleton;
  83112. }());
  83113. BABYLON.Skeleton = Skeleton;
  83114. })(BABYLON || (BABYLON = {}));
  83115. //# sourceMappingURL=babylon.skeleton.js.map
  83116. var BABYLON;
  83117. (function (BABYLON) {
  83118. ;
  83119. /**
  83120. * This groups tools to convert HDR texture to native colors array.
  83121. */
  83122. var HDRTools = /** @class */ (function () {
  83123. function HDRTools() {
  83124. }
  83125. HDRTools.Ldexp = function (mantissa, exponent) {
  83126. if (exponent > 1023) {
  83127. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  83128. }
  83129. if (exponent < -1074) {
  83130. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  83131. }
  83132. return mantissa * Math.pow(2, exponent);
  83133. };
  83134. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  83135. if (exponent > 0) { /*nonzero pixel*/
  83136. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  83137. float32array[index + 0] = red * exponent;
  83138. float32array[index + 1] = green * exponent;
  83139. float32array[index + 2] = blue * exponent;
  83140. }
  83141. else {
  83142. float32array[index + 0] = 0;
  83143. float32array[index + 1] = 0;
  83144. float32array[index + 2] = 0;
  83145. }
  83146. };
  83147. HDRTools.readStringLine = function (uint8array, startIndex) {
  83148. var line = "";
  83149. var character = "";
  83150. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  83151. character = String.fromCharCode(uint8array[i]);
  83152. if (character == "\n") {
  83153. break;
  83154. }
  83155. line += character;
  83156. }
  83157. return line;
  83158. };
  83159. /**
  83160. * Reads header information from an RGBE texture stored in a native array.
  83161. * More information on this format are available here:
  83162. * https://en.wikipedia.org/wiki/RGBE_image_format
  83163. *
  83164. * @param uint8array The binary file stored in native array.
  83165. * @return The header information.
  83166. */
  83167. HDRTools.RGBE_ReadHeader = function (uint8array) {
  83168. var height = 0;
  83169. var width = 0;
  83170. var line = this.readStringLine(uint8array, 0);
  83171. if (line[0] != '#' || line[1] != '?') {
  83172. throw "Bad HDR Format.";
  83173. }
  83174. var endOfHeader = false;
  83175. var findFormat = false;
  83176. var lineIndex = 0;
  83177. do {
  83178. lineIndex += (line.length + 1);
  83179. line = this.readStringLine(uint8array, lineIndex);
  83180. if (line == "FORMAT=32-bit_rle_rgbe") {
  83181. findFormat = true;
  83182. }
  83183. else if (line.length == 0) {
  83184. endOfHeader = true;
  83185. }
  83186. } while (!endOfHeader);
  83187. if (!findFormat) {
  83188. throw "HDR Bad header format, unsupported FORMAT";
  83189. }
  83190. lineIndex += (line.length + 1);
  83191. line = this.readStringLine(uint8array, lineIndex);
  83192. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  83193. var match = sizeRegexp.exec(line);
  83194. // TODO. Support +Y and -X if needed.
  83195. if (!match || match.length < 3) {
  83196. throw "HDR Bad header format, no size";
  83197. }
  83198. width = parseInt(match[2]);
  83199. height = parseInt(match[1]);
  83200. if (width < 8 || width > 0x7fff) {
  83201. throw "HDR Bad header format, unsupported size";
  83202. }
  83203. lineIndex += (line.length + 1);
  83204. return {
  83205. height: height,
  83206. width: width,
  83207. dataPosition: lineIndex
  83208. };
  83209. };
  83210. /**
  83211. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  83212. * This RGBE texture needs to store the information as a panorama.
  83213. *
  83214. * More information on this format are available here:
  83215. * https://en.wikipedia.org/wiki/RGBE_image_format
  83216. *
  83217. * @param buffer The binary file stored in an array buffer.
  83218. * @param size The expected size of the extracted cubemap.
  83219. * @return The Cube Map information.
  83220. */
  83221. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  83222. var uint8array = new Uint8Array(buffer);
  83223. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  83224. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83225. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  83226. return cubeMapData;
  83227. };
  83228. /**
  83229. * Returns the pixels data extracted from an RGBE texture.
  83230. * This pixels will be stored left to right up to down in the R G B order in one array.
  83231. *
  83232. * More information on this format are available here:
  83233. * https://en.wikipedia.org/wiki/RGBE_image_format
  83234. *
  83235. * @param uint8array The binary file stored in an array buffer.
  83236. * @param hdrInfo The header information of the file.
  83237. * @return The pixels data in RGB right to left up to down order.
  83238. */
  83239. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  83240. // Keep for multi format supports.
  83241. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83242. };
  83243. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  83244. var num_scanlines = hdrInfo.height;
  83245. var scanline_width = hdrInfo.width;
  83246. var a, b, c, d, count;
  83247. var dataIndex = hdrInfo.dataPosition;
  83248. var index = 0, endIndex = 0, i = 0;
  83249. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  83250. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  83251. // 3 channels of 4 bytes per pixel in float.
  83252. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  83253. var resultArray = new Float32Array(resultBuffer);
  83254. // read in each successive scanline
  83255. while (num_scanlines > 0) {
  83256. a = uint8array[dataIndex++];
  83257. b = uint8array[dataIndex++];
  83258. c = uint8array[dataIndex++];
  83259. d = uint8array[dataIndex++];
  83260. if (a != 2 || b != 2 || (c & 0x80)) {
  83261. // this file is not run length encoded
  83262. throw "HDR Bad header format, not RLE";
  83263. }
  83264. if (((c << 8) | d) != scanline_width) {
  83265. throw "HDR Bad header format, wrong scan line width";
  83266. }
  83267. index = 0;
  83268. // read each of the four channels for the scanline into the buffer
  83269. for (i = 0; i < 4; i++) {
  83270. endIndex = (i + 1) * scanline_width;
  83271. while (index < endIndex) {
  83272. a = uint8array[dataIndex++];
  83273. b = uint8array[dataIndex++];
  83274. if (a > 128) {
  83275. // a run of the same value
  83276. count = a - 128;
  83277. if ((count == 0) || (count > endIndex - index)) {
  83278. throw "HDR Bad Format, bad scanline data (run)";
  83279. }
  83280. while (count-- > 0) {
  83281. scanLineArray[index++] = b;
  83282. }
  83283. }
  83284. else {
  83285. // a non-run
  83286. count = a;
  83287. if ((count == 0) || (count > endIndex - index)) {
  83288. throw "HDR Bad Format, bad scanline data (non-run)";
  83289. }
  83290. scanLineArray[index++] = b;
  83291. if (--count > 0) {
  83292. for (var j = 0; j < count; j++) {
  83293. scanLineArray[index++] = uint8array[dataIndex++];
  83294. }
  83295. }
  83296. }
  83297. }
  83298. }
  83299. // now convert data from buffer into floats
  83300. for (i = 0; i < scanline_width; i++) {
  83301. a = scanLineArray[i];
  83302. b = scanLineArray[i + scanline_width];
  83303. c = scanLineArray[i + 2 * scanline_width];
  83304. d = scanLineArray[i + 3 * scanline_width];
  83305. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  83306. }
  83307. num_scanlines--;
  83308. }
  83309. return resultArray;
  83310. };
  83311. return HDRTools;
  83312. }());
  83313. BABYLON.HDRTools = HDRTools;
  83314. })(BABYLON || (BABYLON = {}));
  83315. //# sourceMappingURL=babylon.hdr.js.map
  83316. var BABYLON;
  83317. (function (BABYLON) {
  83318. /**
  83319. * This represents a texture coming from an HDR input.
  83320. *
  83321. * The only supported format is currently panorama picture stored in RGBE format.
  83322. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83323. */
  83324. var HDRCubeTexture = /** @class */ (function (_super) {
  83325. __extends(HDRCubeTexture, _super);
  83326. /**
  83327. * Instantiates an HDRTexture from the following parameters.
  83328. *
  83329. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83330. * @param scene The scene the texture will be used in
  83331. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83332. * @param noMipmap Forces to not generate the mipmap if true
  83333. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83334. * @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)
  83335. * @param reserved Reserved flag for internal use.
  83336. */
  83337. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83338. if (noMipmap === void 0) { noMipmap = false; }
  83339. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83340. if (gammaSpace === void 0) { gammaSpace = false; }
  83341. if (reserved === void 0) { reserved = false; }
  83342. if (onLoad === void 0) { onLoad = null; }
  83343. if (onError === void 0) { onError = null; }
  83344. var _this = _super.call(this, scene) || this;
  83345. _this._generateHarmonics = true;
  83346. _this._onLoad = null;
  83347. _this._onError = null;
  83348. /**
  83349. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83350. */
  83351. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83352. _this._isBlocking = true;
  83353. _this._rotationY = 0;
  83354. /**
  83355. * Gets or sets the center of the bounding box associated with the cube texture
  83356. * It must define where the camera used to render the texture was set
  83357. */
  83358. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83359. if (!url) {
  83360. return _this;
  83361. }
  83362. _this.name = url;
  83363. _this.url = url;
  83364. _this.hasAlpha = false;
  83365. _this.isCube = true;
  83366. _this._textureMatrix = BABYLON.Matrix.Identity();
  83367. _this._onLoad = onLoad;
  83368. _this._onError = onError;
  83369. _this.gammaSpace = gammaSpace;
  83370. _this._noMipmap = noMipmap;
  83371. _this._size = size;
  83372. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83373. if (!_this._texture) {
  83374. if (!scene.useDelayedTextureLoading) {
  83375. _this.loadTexture();
  83376. }
  83377. else {
  83378. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83379. }
  83380. }
  83381. return _this;
  83382. }
  83383. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83384. /**
  83385. * Gets wether or not the texture is blocking during loading.
  83386. */
  83387. get: function () {
  83388. return this._isBlocking;
  83389. },
  83390. /**
  83391. * Sets wether or not the texture is blocking during loading.
  83392. */
  83393. set: function (value) {
  83394. this._isBlocking = value;
  83395. },
  83396. enumerable: true,
  83397. configurable: true
  83398. });
  83399. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83400. /**
  83401. * Gets texture matrix rotation angle around Y axis radians.
  83402. */
  83403. get: function () {
  83404. return this._rotationY;
  83405. },
  83406. /**
  83407. * Sets texture matrix rotation angle around Y axis in radians.
  83408. */
  83409. set: function (value) {
  83410. this._rotationY = value;
  83411. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83412. },
  83413. enumerable: true,
  83414. configurable: true
  83415. });
  83416. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83417. get: function () {
  83418. return this._boundingBoxSize;
  83419. },
  83420. /**
  83421. * Gets or sets the size of the bounding box associated with the cube texture
  83422. * When defined, the cubemap will switch to local mode
  83423. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83424. * @example https://www.babylonjs-playground.com/#RNASML
  83425. */
  83426. set: function (value) {
  83427. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83428. return;
  83429. }
  83430. this._boundingBoxSize = value;
  83431. var scene = this.getScene();
  83432. if (scene) {
  83433. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83434. }
  83435. },
  83436. enumerable: true,
  83437. configurable: true
  83438. });
  83439. /**
  83440. * Occurs when the file is raw .hdr file.
  83441. */
  83442. HDRCubeTexture.prototype.loadTexture = function () {
  83443. var _this = this;
  83444. var callback = function (buffer) {
  83445. _this.lodGenerationOffset = 0.0;
  83446. _this.lodGenerationScale = 0.8;
  83447. var scene = _this.getScene();
  83448. if (!scene) {
  83449. return null;
  83450. }
  83451. // Extract the raw linear data.
  83452. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83453. // Generate harmonics if needed.
  83454. if (_this._generateHarmonics) {
  83455. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83456. _this.sphericalPolynomial = sphericalPolynomial;
  83457. }
  83458. var results = [];
  83459. var byteArray = null;
  83460. // Push each faces.
  83461. for (var j = 0; j < 6; j++) {
  83462. // Create uintarray fallback.
  83463. if (!scene.getEngine().getCaps().textureFloat) {
  83464. // 3 channels of 1 bytes per pixel in bytes.
  83465. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83466. byteArray = new Uint8Array(byteBuffer);
  83467. }
  83468. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83469. // If special cases.
  83470. if (_this.gammaSpace || byteArray) {
  83471. for (var i = 0; i < _this._size * _this._size; i++) {
  83472. // Put in gamma space if requested.
  83473. if (_this.gammaSpace) {
  83474. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83475. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83476. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83477. }
  83478. // Convert to int texture for fallback.
  83479. if (byteArray) {
  83480. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83481. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83482. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83483. // May use luminance instead if the result is not accurate.
  83484. var max = Math.max(Math.max(r, g), b);
  83485. if (max > 255) {
  83486. var scale = 255 / max;
  83487. r *= scale;
  83488. g *= scale;
  83489. b *= scale;
  83490. }
  83491. byteArray[(i * 3) + 0] = r;
  83492. byteArray[(i * 3) + 1] = g;
  83493. byteArray[(i * 3) + 2] = b;
  83494. }
  83495. }
  83496. }
  83497. if (byteArray) {
  83498. results.push(byteArray);
  83499. }
  83500. else {
  83501. results.push(dataFace);
  83502. }
  83503. }
  83504. return results;
  83505. };
  83506. var scene = this.getScene();
  83507. if (scene) {
  83508. 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);
  83509. }
  83510. };
  83511. HDRCubeTexture.prototype.clone = function () {
  83512. var scene = this.getScene();
  83513. if (!scene) {
  83514. return this;
  83515. }
  83516. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83517. // Base texture
  83518. newTexture.level = this.level;
  83519. newTexture.wrapU = this.wrapU;
  83520. newTexture.wrapV = this.wrapV;
  83521. newTexture.coordinatesIndex = this.coordinatesIndex;
  83522. newTexture.coordinatesMode = this.coordinatesMode;
  83523. return newTexture;
  83524. };
  83525. // Methods
  83526. HDRCubeTexture.prototype.delayLoad = function () {
  83527. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83528. return;
  83529. }
  83530. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83531. this._texture = this._getFromCache(this.url, this._noMipmap);
  83532. if (!this._texture) {
  83533. this.loadTexture();
  83534. }
  83535. };
  83536. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83537. return this._textureMatrix;
  83538. };
  83539. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83540. this._textureMatrix = value;
  83541. };
  83542. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83543. var texture = null;
  83544. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83545. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83546. texture.name = parsedTexture.name;
  83547. texture.hasAlpha = parsedTexture.hasAlpha;
  83548. texture.level = parsedTexture.level;
  83549. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83550. texture.isBlocking = parsedTexture.isBlocking;
  83551. }
  83552. if (texture) {
  83553. if (parsedTexture.boundingBoxPosition) {
  83554. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83555. }
  83556. if (parsedTexture.boundingBoxSize) {
  83557. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83558. }
  83559. if (parsedTexture.rotationY) {
  83560. texture.rotationY = parsedTexture.rotationY;
  83561. }
  83562. }
  83563. return texture;
  83564. };
  83565. HDRCubeTexture.prototype.serialize = function () {
  83566. if (!this.name) {
  83567. return null;
  83568. }
  83569. var serializationObject = {};
  83570. serializationObject.name = this.name;
  83571. serializationObject.hasAlpha = this.hasAlpha;
  83572. serializationObject.isCube = true;
  83573. serializationObject.level = this.level;
  83574. serializationObject.size = this._size;
  83575. serializationObject.coordinatesMode = this.coordinatesMode;
  83576. serializationObject.useInGammaSpace = this.gammaSpace;
  83577. serializationObject.generateHarmonics = this._generateHarmonics;
  83578. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83579. serializationObject.noMipmap = this._noMipmap;
  83580. serializationObject.isBlocking = this._isBlocking;
  83581. serializationObject.rotationY = this._rotationY;
  83582. return serializationObject;
  83583. };
  83584. HDRCubeTexture._facesMapping = [
  83585. "right",
  83586. "left",
  83587. "up",
  83588. "down",
  83589. "front",
  83590. "back"
  83591. ];
  83592. return HDRCubeTexture;
  83593. }(BABYLON.BaseTexture));
  83594. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83595. })(BABYLON || (BABYLON = {}));
  83596. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83597. var BABYLON;
  83598. (function (BABYLON) {
  83599. /**
  83600. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  83601. */
  83602. var PanoramaToCubeMapTools = /** @class */ (function () {
  83603. function PanoramaToCubeMapTools() {
  83604. }
  83605. /**
  83606. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  83607. *
  83608. * @param float32Array The source data.
  83609. * @param inputWidth The width of the input panorama.
  83610. * @param inputhHeight The height of the input panorama.
  83611. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  83612. * @return The cubemap data
  83613. */
  83614. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  83615. if (!float32Array) {
  83616. throw "ConvertPanoramaToCubemap: input cannot be null";
  83617. }
  83618. if (float32Array.length != inputWidth * inputHeight * 3) {
  83619. throw "ConvertPanoramaToCubemap: input size is wrong";
  83620. }
  83621. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  83622. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  83623. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  83624. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  83625. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  83626. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  83627. return {
  83628. front: textureFront,
  83629. back: textureBack,
  83630. left: textureLeft,
  83631. right: textureRight,
  83632. up: textureUp,
  83633. down: textureDown,
  83634. size: size,
  83635. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  83636. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  83637. gammaSpace: false,
  83638. };
  83639. };
  83640. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  83641. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  83642. var textureArray = new Float32Array(buffer);
  83643. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  83644. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  83645. var dy = 1 / texSize;
  83646. var fy = 0;
  83647. for (var y = 0; y < texSize; y++) {
  83648. var xv1 = faceData[0];
  83649. var xv2 = faceData[2];
  83650. for (var x = 0; x < texSize; x++) {
  83651. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  83652. v.normalize();
  83653. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  83654. // 3 channels per pixels
  83655. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  83656. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  83657. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  83658. xv1 = xv1.add(rotDX1);
  83659. xv2 = xv2.add(rotDX2);
  83660. }
  83661. fy += dy;
  83662. }
  83663. return textureArray;
  83664. };
  83665. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  83666. var theta = Math.atan2(vDir.z, vDir.x);
  83667. var phi = Math.acos(vDir.y);
  83668. while (theta < -Math.PI)
  83669. theta += 2 * Math.PI;
  83670. while (theta > Math.PI)
  83671. theta -= 2 * Math.PI;
  83672. var dx = theta / Math.PI;
  83673. var dy = phi / Math.PI;
  83674. // recenter.
  83675. dx = dx * 0.5 + 0.5;
  83676. var px = Math.round(dx * inputWidth);
  83677. if (px < 0)
  83678. px = 0;
  83679. else if (px >= inputWidth)
  83680. px = inputWidth - 1;
  83681. var py = Math.round(dy * inputHeight);
  83682. if (py < 0)
  83683. py = 0;
  83684. else if (py >= inputHeight)
  83685. py = inputHeight - 1;
  83686. var inputY = (inputHeight - py - 1);
  83687. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  83688. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  83689. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  83690. return {
  83691. r: r,
  83692. g: g,
  83693. b: b
  83694. };
  83695. };
  83696. PanoramaToCubeMapTools.FACE_FRONT = [
  83697. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83698. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83699. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83700. new BABYLON.Vector3(1.0, 1.0, -1.0)
  83701. ];
  83702. PanoramaToCubeMapTools.FACE_BACK = [
  83703. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83704. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83705. new BABYLON.Vector3(1.0, 1.0, 1.0),
  83706. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  83707. ];
  83708. PanoramaToCubeMapTools.FACE_RIGHT = [
  83709. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83710. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83711. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83712. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83713. ];
  83714. PanoramaToCubeMapTools.FACE_LEFT = [
  83715. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83716. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83717. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83718. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  83719. ];
  83720. PanoramaToCubeMapTools.FACE_DOWN = [
  83721. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83722. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83723. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83724. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83725. ];
  83726. PanoramaToCubeMapTools.FACE_UP = [
  83727. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83728. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83729. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83730. new BABYLON.Vector3(1.0, -1.0, -1.0)
  83731. ];
  83732. return PanoramaToCubeMapTools;
  83733. }());
  83734. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  83735. })(BABYLON || (BABYLON = {}));
  83736. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  83737. var BABYLON;
  83738. (function (BABYLON) {
  83739. var IndexedVector2 = /** @class */ (function (_super) {
  83740. __extends(IndexedVector2, _super);
  83741. function IndexedVector2(original, index) {
  83742. var _this = _super.call(this, original.x, original.y) || this;
  83743. _this.index = index;
  83744. return _this;
  83745. }
  83746. return IndexedVector2;
  83747. }(BABYLON.Vector2));
  83748. var PolygonPoints = /** @class */ (function () {
  83749. function PolygonPoints() {
  83750. this.elements = new Array();
  83751. }
  83752. PolygonPoints.prototype.add = function (originalPoints) {
  83753. var _this = this;
  83754. var result = new Array();
  83755. originalPoints.forEach(function (point) {
  83756. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83757. var newPoint = new IndexedVector2(point, _this.elements.length);
  83758. result.push(newPoint);
  83759. _this.elements.push(newPoint);
  83760. }
  83761. });
  83762. return result;
  83763. };
  83764. PolygonPoints.prototype.computeBounds = function () {
  83765. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83766. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83767. this.elements.forEach(function (point) {
  83768. // x
  83769. if (point.x < lmin.x) {
  83770. lmin.x = point.x;
  83771. }
  83772. else if (point.x > lmax.x) {
  83773. lmax.x = point.x;
  83774. }
  83775. // y
  83776. if (point.y < lmin.y) {
  83777. lmin.y = point.y;
  83778. }
  83779. else if (point.y > lmax.y) {
  83780. lmax.y = point.y;
  83781. }
  83782. });
  83783. return {
  83784. min: lmin,
  83785. max: lmax,
  83786. width: lmax.x - lmin.x,
  83787. height: lmax.y - lmin.y
  83788. };
  83789. };
  83790. return PolygonPoints;
  83791. }());
  83792. var Polygon = /** @class */ (function () {
  83793. function Polygon() {
  83794. }
  83795. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83796. return [
  83797. new BABYLON.Vector2(xmin, ymin),
  83798. new BABYLON.Vector2(xmax, ymin),
  83799. new BABYLON.Vector2(xmax, ymax),
  83800. new BABYLON.Vector2(xmin, ymax)
  83801. ];
  83802. };
  83803. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83804. if (cx === void 0) { cx = 0; }
  83805. if (cy === void 0) { cy = 0; }
  83806. if (numberOfSides === void 0) { numberOfSides = 32; }
  83807. var result = new Array();
  83808. var angle = 0;
  83809. var increment = (Math.PI * 2) / numberOfSides;
  83810. for (var i = 0; i < numberOfSides; i++) {
  83811. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83812. angle -= increment;
  83813. }
  83814. return result;
  83815. };
  83816. Polygon.Parse = function (input) {
  83817. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83818. var i, result = [];
  83819. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83820. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83821. }
  83822. return result;
  83823. };
  83824. Polygon.StartingAt = function (x, y) {
  83825. return BABYLON.Path2.StartingAt(x, y);
  83826. };
  83827. return Polygon;
  83828. }());
  83829. BABYLON.Polygon = Polygon;
  83830. var PolygonMeshBuilder = /** @class */ (function () {
  83831. function PolygonMeshBuilder(name, contours, scene) {
  83832. this._points = new PolygonPoints();
  83833. this._outlinepoints = new PolygonPoints();
  83834. this._holes = new Array();
  83835. this._epoints = new Array();
  83836. this._eholes = new Array();
  83837. this._name = name;
  83838. this._scene = scene;
  83839. var points;
  83840. if (contours instanceof BABYLON.Path2) {
  83841. points = contours.getPoints();
  83842. }
  83843. else {
  83844. points = contours;
  83845. }
  83846. this._addToepoint(points);
  83847. this._points.add(points);
  83848. this._outlinepoints.add(points);
  83849. if (typeof earcut === 'undefined') {
  83850. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83851. }
  83852. }
  83853. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83854. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83855. var p = points_1[_i];
  83856. this._epoints.push(p.x, p.y);
  83857. }
  83858. };
  83859. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83860. this._points.add(hole);
  83861. var holepoints = new PolygonPoints();
  83862. holepoints.add(hole);
  83863. this._holes.push(holepoints);
  83864. this._eholes.push(this._epoints.length / 2);
  83865. this._addToepoint(hole);
  83866. return this;
  83867. };
  83868. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83869. var _this = this;
  83870. if (updatable === void 0) { updatable = false; }
  83871. if (depth === void 0) { depth = 0; }
  83872. var result = new BABYLON.Mesh(this._name, this._scene);
  83873. var normals = new Array();
  83874. var positions = new Array();
  83875. var uvs = new Array();
  83876. var bounds = this._points.computeBounds();
  83877. this._points.elements.forEach(function (p) {
  83878. normals.push(0, 1.0, 0);
  83879. positions.push(p.x, 0, p.y);
  83880. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83881. });
  83882. var indices = new Array();
  83883. var res = earcut(this._epoints, this._eholes, 2);
  83884. for (var i = 0; i < res.length; i++) {
  83885. indices.push(res[i]);
  83886. }
  83887. if (depth > 0) {
  83888. var positionscount = (positions.length / 3); //get the current pointcount
  83889. this._points.elements.forEach(function (p) {
  83890. normals.push(0, -1.0, 0);
  83891. positions.push(p.x, -depth, p.y);
  83892. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83893. });
  83894. var totalCount = indices.length;
  83895. for (var i = 0; i < totalCount; i += 3) {
  83896. var i0 = indices[i + 0];
  83897. var i1 = indices[i + 1];
  83898. var i2 = indices[i + 2];
  83899. indices.push(i2 + positionscount);
  83900. indices.push(i1 + positionscount);
  83901. indices.push(i0 + positionscount);
  83902. }
  83903. //Add the sides
  83904. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83905. this._holes.forEach(function (hole) {
  83906. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83907. });
  83908. }
  83909. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83910. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83911. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83912. result.setIndices(indices);
  83913. return result;
  83914. };
  83915. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83916. var StartIndex = positions.length / 3;
  83917. var ulength = 0;
  83918. for (var i = 0; i < points.elements.length; i++) {
  83919. var p = points.elements[i];
  83920. var p1;
  83921. if ((i + 1) > points.elements.length - 1) {
  83922. p1 = points.elements[0];
  83923. }
  83924. else {
  83925. p1 = points.elements[i + 1];
  83926. }
  83927. positions.push(p.x, 0, p.y);
  83928. positions.push(p.x, -depth, p.y);
  83929. positions.push(p1.x, 0, p1.y);
  83930. positions.push(p1.x, -depth, p1.y);
  83931. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83932. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83933. var v3 = v2.subtract(v1);
  83934. var v4 = new BABYLON.Vector3(0, 1, 0);
  83935. var vn = BABYLON.Vector3.Cross(v3, v4);
  83936. vn = vn.normalize();
  83937. uvs.push(ulength / bounds.width, 0);
  83938. uvs.push(ulength / bounds.width, 1);
  83939. ulength += v3.length();
  83940. uvs.push((ulength / bounds.width), 0);
  83941. uvs.push((ulength / bounds.width), 1);
  83942. if (!flip) {
  83943. normals.push(-vn.x, -vn.y, -vn.z);
  83944. normals.push(-vn.x, -vn.y, -vn.z);
  83945. normals.push(-vn.x, -vn.y, -vn.z);
  83946. normals.push(-vn.x, -vn.y, -vn.z);
  83947. indices.push(StartIndex);
  83948. indices.push(StartIndex + 1);
  83949. indices.push(StartIndex + 2);
  83950. indices.push(StartIndex + 1);
  83951. indices.push(StartIndex + 3);
  83952. indices.push(StartIndex + 2);
  83953. }
  83954. else {
  83955. normals.push(vn.x, vn.y, vn.z);
  83956. normals.push(vn.x, vn.y, vn.z);
  83957. normals.push(vn.x, vn.y, vn.z);
  83958. normals.push(vn.x, vn.y, vn.z);
  83959. indices.push(StartIndex);
  83960. indices.push(StartIndex + 2);
  83961. indices.push(StartIndex + 1);
  83962. indices.push(StartIndex + 1);
  83963. indices.push(StartIndex + 2);
  83964. indices.push(StartIndex + 3);
  83965. }
  83966. StartIndex += 4;
  83967. }
  83968. ;
  83969. };
  83970. return PolygonMeshBuilder;
  83971. }());
  83972. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83973. })(BABYLON || (BABYLON = {}));
  83974. //# sourceMappingURL=babylon.polygonMesh.js.map
  83975. var BABYLON;
  83976. (function (BABYLON) {
  83977. // Unique ID when we import meshes from Babylon to CSG
  83978. var currentCSGMeshId = 0;
  83979. // # class Vertex
  83980. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83981. // one to provide additional features like texture coordinates and vertex
  83982. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83983. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83984. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83985. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83986. // is not used anywhere else.
  83987. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83988. var Vertex = /** @class */ (function () {
  83989. function Vertex(pos, normal, uv) {
  83990. this.pos = pos;
  83991. this.normal = normal;
  83992. this.uv = uv;
  83993. }
  83994. Vertex.prototype.clone = function () {
  83995. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83996. };
  83997. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83998. // orientation of a polygon is flipped.
  83999. Vertex.prototype.flip = function () {
  84000. this.normal = this.normal.scale(-1);
  84001. };
  84002. // Create a new vertex between this vertex and `other` by linearly
  84003. // interpolating all properties using a parameter of `t`. Subclasses should
  84004. // override this to interpolate additional properties.
  84005. Vertex.prototype.interpolate = function (other, t) {
  84006. 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));
  84007. };
  84008. return Vertex;
  84009. }());
  84010. // # class Plane
  84011. // Represents a plane in 3D space.
  84012. var Plane = /** @class */ (function () {
  84013. function Plane(normal, w) {
  84014. this.normal = normal;
  84015. this.w = w;
  84016. }
  84017. Plane.FromPoints = function (a, b, c) {
  84018. var v0 = c.subtract(a);
  84019. var v1 = b.subtract(a);
  84020. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  84021. return null;
  84022. }
  84023. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  84024. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  84025. };
  84026. Plane.prototype.clone = function () {
  84027. return new Plane(this.normal.clone(), this.w);
  84028. };
  84029. Plane.prototype.flip = function () {
  84030. this.normal.scaleInPlace(-1);
  84031. this.w = -this.w;
  84032. };
  84033. // Split `polygon` by this plane if needed, then put the polygon or polygon
  84034. // fragments in the appropriate lists. Coplanar polygons go into either
  84035. // `coplanarFront` or `coplanarBack` depending on their orientation with
  84036. // respect to this plane. Polygons in front or in back of this plane go into
  84037. // either `front` or `back`.
  84038. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  84039. var COPLANAR = 0;
  84040. var FRONT = 1;
  84041. var BACK = 2;
  84042. var SPANNING = 3;
  84043. // Classify each point as well as the entire polygon into one of the above
  84044. // four classes.
  84045. var polygonType = 0;
  84046. var types = [];
  84047. var i;
  84048. var t;
  84049. for (i = 0; i < polygon.vertices.length; i++) {
  84050. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  84051. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  84052. polygonType |= type;
  84053. types.push(type);
  84054. }
  84055. // Put the polygon in the correct list, splitting it when necessary.
  84056. switch (polygonType) {
  84057. case COPLANAR:
  84058. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  84059. break;
  84060. case FRONT:
  84061. front.push(polygon);
  84062. break;
  84063. case BACK:
  84064. back.push(polygon);
  84065. break;
  84066. case SPANNING:
  84067. var f = [], b = [];
  84068. for (i = 0; i < polygon.vertices.length; i++) {
  84069. var j = (i + 1) % polygon.vertices.length;
  84070. var ti = types[i], tj = types[j];
  84071. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  84072. if (ti !== BACK)
  84073. f.push(vi);
  84074. if (ti !== FRONT)
  84075. b.push(ti !== BACK ? vi.clone() : vi);
  84076. if ((ti | tj) === SPANNING) {
  84077. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  84078. var v = vi.interpolate(vj, t);
  84079. f.push(v);
  84080. b.push(v.clone());
  84081. }
  84082. }
  84083. var poly;
  84084. if (f.length >= 3) {
  84085. poly = new Polygon(f, polygon.shared);
  84086. if (poly.plane)
  84087. front.push(poly);
  84088. }
  84089. if (b.length >= 3) {
  84090. poly = new Polygon(b, polygon.shared);
  84091. if (poly.plane)
  84092. back.push(poly);
  84093. }
  84094. break;
  84095. }
  84096. };
  84097. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  84098. // point is on the plane.
  84099. Plane.EPSILON = 1e-5;
  84100. return Plane;
  84101. }());
  84102. // # class Polygon
  84103. // Represents a convex polygon. The vertices used to initialize a polygon must
  84104. // be coplanar and form a convex loop.
  84105. //
  84106. // Each convex polygon has a `shared` property, which is shared between all
  84107. // polygons that are clones of each other or were split from the same polygon.
  84108. // This can be used to define per-polygon properties (such as surface color).
  84109. var Polygon = /** @class */ (function () {
  84110. function Polygon(vertices, shared) {
  84111. this.vertices = vertices;
  84112. this.shared = shared;
  84113. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  84114. }
  84115. Polygon.prototype.clone = function () {
  84116. var vertices = this.vertices.map(function (v) { return v.clone(); });
  84117. return new Polygon(vertices, this.shared);
  84118. };
  84119. Polygon.prototype.flip = function () {
  84120. this.vertices.reverse().map(function (v) { v.flip(); });
  84121. this.plane.flip();
  84122. };
  84123. return Polygon;
  84124. }());
  84125. // # class Node
  84126. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  84127. // by picking a polygon to split along. That polygon (and all other coplanar
  84128. // polygons) are added directly to that node and the other polygons are added to
  84129. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  84130. // no distinction between internal and leaf nodes.
  84131. var Node = /** @class */ (function () {
  84132. function Node(polygons) {
  84133. this.plane = null;
  84134. this.front = null;
  84135. this.back = null;
  84136. this.polygons = new Array();
  84137. if (polygons) {
  84138. this.build(polygons);
  84139. }
  84140. }
  84141. Node.prototype.clone = function () {
  84142. var node = new Node();
  84143. node.plane = this.plane && this.plane.clone();
  84144. node.front = this.front && this.front.clone();
  84145. node.back = this.back && this.back.clone();
  84146. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  84147. return node;
  84148. };
  84149. // Convert solid space to empty space and empty space to solid space.
  84150. Node.prototype.invert = function () {
  84151. for (var i = 0; i < this.polygons.length; i++) {
  84152. this.polygons[i].flip();
  84153. }
  84154. if (this.plane) {
  84155. this.plane.flip();
  84156. }
  84157. if (this.front) {
  84158. this.front.invert();
  84159. }
  84160. if (this.back) {
  84161. this.back.invert();
  84162. }
  84163. var temp = this.front;
  84164. this.front = this.back;
  84165. this.back = temp;
  84166. };
  84167. // Recursively remove all polygons in `polygons` that are inside this BSP
  84168. // tree.
  84169. Node.prototype.clipPolygons = function (polygons) {
  84170. if (!this.plane)
  84171. return polygons.slice();
  84172. var front = new Array(), back = new Array();
  84173. for (var i = 0; i < polygons.length; i++) {
  84174. this.plane.splitPolygon(polygons[i], front, back, front, back);
  84175. }
  84176. if (this.front) {
  84177. front = this.front.clipPolygons(front);
  84178. }
  84179. if (this.back) {
  84180. back = this.back.clipPolygons(back);
  84181. }
  84182. else {
  84183. back = [];
  84184. }
  84185. return front.concat(back);
  84186. };
  84187. // Remove all polygons in this BSP tree that are inside the other BSP tree
  84188. // `bsp`.
  84189. Node.prototype.clipTo = function (bsp) {
  84190. this.polygons = bsp.clipPolygons(this.polygons);
  84191. if (this.front)
  84192. this.front.clipTo(bsp);
  84193. if (this.back)
  84194. this.back.clipTo(bsp);
  84195. };
  84196. // Return a list of all polygons in this BSP tree.
  84197. Node.prototype.allPolygons = function () {
  84198. var polygons = this.polygons.slice();
  84199. if (this.front)
  84200. polygons = polygons.concat(this.front.allPolygons());
  84201. if (this.back)
  84202. polygons = polygons.concat(this.back.allPolygons());
  84203. return polygons;
  84204. };
  84205. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  84206. // new polygons are filtered down to the bottom of the tree and become new
  84207. // nodes there. Each set of polygons is partitioned using the first polygon
  84208. // (no heuristic is used to pick a good split).
  84209. Node.prototype.build = function (polygons) {
  84210. if (!polygons.length)
  84211. return;
  84212. if (!this.plane)
  84213. this.plane = polygons[0].plane.clone();
  84214. var front = new Array(), back = new Array();
  84215. for (var i = 0; i < polygons.length; i++) {
  84216. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  84217. }
  84218. if (front.length) {
  84219. if (!this.front)
  84220. this.front = new Node();
  84221. this.front.build(front);
  84222. }
  84223. if (back.length) {
  84224. if (!this.back)
  84225. this.back = new Node();
  84226. this.back.build(back);
  84227. }
  84228. };
  84229. return Node;
  84230. }());
  84231. var CSG = /** @class */ (function () {
  84232. function CSG() {
  84233. this.polygons = new Array();
  84234. }
  84235. // Convert BABYLON.Mesh to BABYLON.CSG
  84236. CSG.FromMesh = function (mesh) {
  84237. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  84238. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  84239. if (mesh instanceof BABYLON.Mesh) {
  84240. mesh.computeWorldMatrix(true);
  84241. matrix = mesh.getWorldMatrix();
  84242. meshPosition = mesh.position.clone();
  84243. meshRotation = mesh.rotation.clone();
  84244. if (mesh.rotationQuaternion) {
  84245. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  84246. }
  84247. meshScaling = mesh.scaling.clone();
  84248. }
  84249. else {
  84250. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  84251. }
  84252. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84253. var subMeshes = mesh.subMeshes;
  84254. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  84255. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  84256. vertices = [];
  84257. for (var j = 0; j < 3; j++) {
  84258. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  84259. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  84260. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  84261. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  84262. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  84263. vertex = new Vertex(position, normal, uv);
  84264. vertices.push(vertex);
  84265. }
  84266. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  84267. // To handle the case of degenerated triangle
  84268. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  84269. if (polygon.plane)
  84270. polygons.push(polygon);
  84271. }
  84272. }
  84273. var csg = CSG.FromPolygons(polygons);
  84274. csg.matrix = matrix;
  84275. csg.position = meshPosition;
  84276. csg.rotation = meshRotation;
  84277. csg.scaling = meshScaling;
  84278. csg.rotationQuaternion = meshRotationQuaternion;
  84279. currentCSGMeshId++;
  84280. return csg;
  84281. };
  84282. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  84283. CSG.FromPolygons = function (polygons) {
  84284. var csg = new CSG();
  84285. csg.polygons = polygons;
  84286. return csg;
  84287. };
  84288. CSG.prototype.clone = function () {
  84289. var csg = new CSG();
  84290. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  84291. csg.copyTransformAttributes(this);
  84292. return csg;
  84293. };
  84294. CSG.prototype.union = function (csg) {
  84295. var a = new Node(this.clone().polygons);
  84296. var b = new Node(csg.clone().polygons);
  84297. a.clipTo(b);
  84298. b.clipTo(a);
  84299. b.invert();
  84300. b.clipTo(a);
  84301. b.invert();
  84302. a.build(b.allPolygons());
  84303. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84304. };
  84305. CSG.prototype.unionInPlace = function (csg) {
  84306. var a = new Node(this.polygons);
  84307. var b = new Node(csg.polygons);
  84308. a.clipTo(b);
  84309. b.clipTo(a);
  84310. b.invert();
  84311. b.clipTo(a);
  84312. b.invert();
  84313. a.build(b.allPolygons());
  84314. this.polygons = a.allPolygons();
  84315. };
  84316. CSG.prototype.subtract = function (csg) {
  84317. var a = new Node(this.clone().polygons);
  84318. var b = new Node(csg.clone().polygons);
  84319. a.invert();
  84320. a.clipTo(b);
  84321. b.clipTo(a);
  84322. b.invert();
  84323. b.clipTo(a);
  84324. b.invert();
  84325. a.build(b.allPolygons());
  84326. a.invert();
  84327. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84328. };
  84329. CSG.prototype.subtractInPlace = function (csg) {
  84330. var a = new Node(this.polygons);
  84331. var b = new Node(csg.polygons);
  84332. a.invert();
  84333. a.clipTo(b);
  84334. b.clipTo(a);
  84335. b.invert();
  84336. b.clipTo(a);
  84337. b.invert();
  84338. a.build(b.allPolygons());
  84339. a.invert();
  84340. this.polygons = a.allPolygons();
  84341. };
  84342. CSG.prototype.intersect = function (csg) {
  84343. var a = new Node(this.clone().polygons);
  84344. var b = new Node(csg.clone().polygons);
  84345. a.invert();
  84346. b.clipTo(a);
  84347. b.invert();
  84348. a.clipTo(b);
  84349. b.clipTo(a);
  84350. a.build(b.allPolygons());
  84351. a.invert();
  84352. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84353. };
  84354. CSG.prototype.intersectInPlace = function (csg) {
  84355. var a = new Node(this.polygons);
  84356. var b = new Node(csg.polygons);
  84357. a.invert();
  84358. b.clipTo(a);
  84359. b.invert();
  84360. a.clipTo(b);
  84361. b.clipTo(a);
  84362. a.build(b.allPolygons());
  84363. a.invert();
  84364. this.polygons = a.allPolygons();
  84365. };
  84366. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84367. // not modified.
  84368. CSG.prototype.inverse = function () {
  84369. var csg = this.clone();
  84370. csg.inverseInPlace();
  84371. return csg;
  84372. };
  84373. CSG.prototype.inverseInPlace = function () {
  84374. this.polygons.map(function (p) { p.flip(); });
  84375. };
  84376. // This is used to keep meshes transformations so they can be restored
  84377. // when we build back a Babylon Mesh
  84378. // NB : All CSG operations are performed in world coordinates
  84379. CSG.prototype.copyTransformAttributes = function (csg) {
  84380. this.matrix = csg.matrix;
  84381. this.position = csg.position;
  84382. this.rotation = csg.rotation;
  84383. this.scaling = csg.scaling;
  84384. this.rotationQuaternion = csg.rotationQuaternion;
  84385. return this;
  84386. };
  84387. // Build Raw mesh from CSG
  84388. // Coordinates here are in world space
  84389. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84390. var matrix = this.matrix.clone();
  84391. matrix.invert();
  84392. 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;
  84393. if (keepSubMeshes) {
  84394. // Sort Polygons, since subMeshes are indices range
  84395. polygons.sort(function (a, b) {
  84396. if (a.shared.meshId === b.shared.meshId) {
  84397. return a.shared.subMeshId - b.shared.subMeshId;
  84398. }
  84399. else {
  84400. return a.shared.meshId - b.shared.meshId;
  84401. }
  84402. });
  84403. }
  84404. for (var i = 0, il = polygons.length; i < il; i++) {
  84405. polygon = polygons[i];
  84406. // Building SubMeshes
  84407. if (!subMesh_dict[polygon.shared.meshId]) {
  84408. subMesh_dict[polygon.shared.meshId] = {};
  84409. }
  84410. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84411. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84412. indexStart: +Infinity,
  84413. indexEnd: -Infinity,
  84414. materialIndex: polygon.shared.materialIndex
  84415. };
  84416. }
  84417. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84418. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84419. polygonIndices[0] = 0;
  84420. polygonIndices[1] = j - 1;
  84421. polygonIndices[2] = j;
  84422. for (var k = 0; k < 3; k++) {
  84423. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84424. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84425. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84426. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84427. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84428. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84429. // Check if 2 points can be merged
  84430. if (!(typeof vertex_idx !== 'undefined' &&
  84431. normals[vertex_idx * 3] === localNormal.x &&
  84432. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84433. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84434. uvs[vertex_idx * 2] === uv.x &&
  84435. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84436. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84437. uvs.push(uv.x, uv.y);
  84438. normals.push(normal.x, normal.y, normal.z);
  84439. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84440. }
  84441. indices.push(vertex_idx);
  84442. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84443. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84444. currentIndex++;
  84445. }
  84446. }
  84447. }
  84448. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84449. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84450. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84451. mesh.setIndices(indices, null);
  84452. if (keepSubMeshes) {
  84453. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84454. var materialIndexOffset = 0, materialMaxIndex;
  84455. mesh.subMeshes = new Array();
  84456. for (var m in subMesh_dict) {
  84457. materialMaxIndex = -1;
  84458. for (var sm in subMesh_dict[m]) {
  84459. subMesh_obj = subMesh_dict[m][sm];
  84460. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84461. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84462. }
  84463. materialIndexOffset += ++materialMaxIndex;
  84464. }
  84465. }
  84466. return mesh;
  84467. };
  84468. // Build Mesh from CSG taking material and transforms into account
  84469. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84470. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84471. mesh.material = material;
  84472. mesh.position.copyFrom(this.position);
  84473. mesh.rotation.copyFrom(this.rotation);
  84474. if (this.rotationQuaternion) {
  84475. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84476. }
  84477. mesh.scaling.copyFrom(this.scaling);
  84478. mesh.computeWorldMatrix(true);
  84479. return mesh;
  84480. };
  84481. return CSG;
  84482. }());
  84483. BABYLON.CSG = CSG;
  84484. })(BABYLON || (BABYLON = {}));
  84485. //# sourceMappingURL=babylon.csg.js.map
  84486. var BABYLON;
  84487. (function (BABYLON) {
  84488. var LensFlare = /** @class */ (function () {
  84489. function LensFlare(size, position, color, imgUrl, system) {
  84490. this.size = size;
  84491. this.position = position;
  84492. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84493. this.color = color || new BABYLON.Color3(1, 1, 1);
  84494. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84495. this._system = system;
  84496. system.lensFlares.push(this);
  84497. }
  84498. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84499. return new LensFlare(size, position, color, imgUrl, system);
  84500. };
  84501. LensFlare.prototype.dispose = function () {
  84502. if (this.texture) {
  84503. this.texture.dispose();
  84504. }
  84505. // Remove from scene
  84506. var index = this._system.lensFlares.indexOf(this);
  84507. this._system.lensFlares.splice(index, 1);
  84508. };
  84509. ;
  84510. return LensFlare;
  84511. }());
  84512. BABYLON.LensFlare = LensFlare;
  84513. })(BABYLON || (BABYLON = {}));
  84514. //# sourceMappingURL=babylon.lensFlare.js.map
  84515. var BABYLON;
  84516. (function (BABYLON) {
  84517. // Adds the parser to the scene parsers.
  84518. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84519. // Lens flares
  84520. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84521. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84522. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84523. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84524. container.lensFlareSystems.push(lf);
  84525. }
  84526. }
  84527. });
  84528. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84529. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84530. if (this.lensFlareSystems[index].name === name) {
  84531. return this.lensFlareSystems[index];
  84532. }
  84533. }
  84534. return null;
  84535. };
  84536. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84537. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84538. if (this.lensFlareSystems[index].id === id) {
  84539. return this.lensFlareSystems[index];
  84540. }
  84541. }
  84542. return null;
  84543. };
  84544. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84545. var index = this.lensFlareSystems.indexOf(toRemove);
  84546. if (index !== -1) {
  84547. this.lensFlareSystems.splice(index, 1);
  84548. }
  84549. return index;
  84550. };
  84551. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84552. this.lensFlareSystems.push(newLensFlareSystem);
  84553. };
  84554. /**
  84555. * Defines the lens flare scene component responsible to manage any lens flares
  84556. * in a given scene.
  84557. */
  84558. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84559. /**
  84560. * Creates a new instance of the component for the given scene
  84561. * @param scene Defines the scene to register the component in
  84562. */
  84563. function LensFlareSystemSceneComponent(scene) {
  84564. /**
  84565. * The component name helpfull to identify the component in the list of scene components.
  84566. */
  84567. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84568. this.scene = scene;
  84569. scene.lensFlareSystems = new Array();
  84570. }
  84571. /**
  84572. * Registers the component in a given scene
  84573. */
  84574. LensFlareSystemSceneComponent.prototype.register = function () {
  84575. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84576. };
  84577. /**
  84578. * Rebuilds the elements related to this component in case of
  84579. * context lost for instance.
  84580. */
  84581. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84582. // Nothing to do for lens flare
  84583. };
  84584. /**
  84585. * Adds all the element from the container to the scene
  84586. * @param container the container holding the elements
  84587. */
  84588. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84589. var _this = this;
  84590. if (!container.lensFlareSystems) {
  84591. return;
  84592. }
  84593. container.lensFlareSystems.forEach(function (o) {
  84594. _this.scene.addLensFlareSystem(o);
  84595. });
  84596. };
  84597. /**
  84598. * Removes all the elements in the container from the scene
  84599. * @param container contains the elements to remove
  84600. */
  84601. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84602. var _this = this;
  84603. if (!container.lensFlareSystems) {
  84604. return;
  84605. }
  84606. container.lensFlareSystems.forEach(function (o) {
  84607. _this.scene.removeLensFlareSystem(o);
  84608. });
  84609. };
  84610. /**
  84611. * Serializes the component data to the specified json object
  84612. * @param serializationObject The object to serialize to
  84613. */
  84614. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84615. // Lens flares
  84616. serializationObject.lensFlareSystems = [];
  84617. var lensFlareSystems = this.scene.lensFlareSystems;
  84618. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84619. var lensFlareSystem = lensFlareSystems_1[_i];
  84620. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84621. }
  84622. };
  84623. /**
  84624. * Disposes the component and the associated ressources.
  84625. */
  84626. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84627. var lensFlareSystems = this.scene.lensFlareSystems;
  84628. while (lensFlareSystems.length) {
  84629. lensFlareSystems[0].dispose();
  84630. }
  84631. };
  84632. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84633. // Lens flares
  84634. if (this.scene.lensFlaresEnabled) {
  84635. var lensFlareSystems = this.scene.lensFlareSystems;
  84636. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84637. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84638. var lensFlareSystem = lensFlareSystems_2[_i];
  84639. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84640. lensFlareSystem.render();
  84641. }
  84642. }
  84643. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84644. }
  84645. };
  84646. return LensFlareSystemSceneComponent;
  84647. }());
  84648. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84649. })(BABYLON || (BABYLON = {}));
  84650. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84651. var BABYLON;
  84652. (function (BABYLON) {
  84653. var LensFlareSystem = /** @class */ (function () {
  84654. function LensFlareSystem(name, emitter, scene) {
  84655. this.name = name;
  84656. this.lensFlares = new Array();
  84657. this.borderLimit = 300;
  84658. this.viewportBorder = 0;
  84659. this.layerMask = 0x0FFFFFFF;
  84660. this._vertexBuffers = {};
  84661. this._isEnabled = true;
  84662. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84663. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84664. if (!component) {
  84665. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84666. scene._addComponent(component);
  84667. }
  84668. this._emitter = emitter;
  84669. this.id = name;
  84670. scene.lensFlareSystems.push(this);
  84671. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84672. var engine = scene.getEngine();
  84673. // VBO
  84674. var vertices = [];
  84675. vertices.push(1, 1);
  84676. vertices.push(-1, 1);
  84677. vertices.push(-1, -1);
  84678. vertices.push(1, -1);
  84679. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84680. // Indices
  84681. var indices = [];
  84682. indices.push(0);
  84683. indices.push(1);
  84684. indices.push(2);
  84685. indices.push(0);
  84686. indices.push(2);
  84687. indices.push(3);
  84688. this._indexBuffer = engine.createIndexBuffer(indices);
  84689. // Effects
  84690. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84691. }
  84692. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84693. get: function () {
  84694. return this._isEnabled;
  84695. },
  84696. set: function (value) {
  84697. this._isEnabled = value;
  84698. },
  84699. enumerable: true,
  84700. configurable: true
  84701. });
  84702. LensFlareSystem.prototype.getScene = function () {
  84703. return this._scene;
  84704. };
  84705. LensFlareSystem.prototype.getEmitter = function () {
  84706. return this._emitter;
  84707. };
  84708. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84709. this._emitter = newEmitter;
  84710. };
  84711. LensFlareSystem.prototype.getEmitterPosition = function () {
  84712. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84713. };
  84714. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84715. var position = this.getEmitterPosition();
  84716. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84717. this._positionX = position.x;
  84718. this._positionY = position.y;
  84719. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84720. if (this.viewportBorder > 0) {
  84721. globalViewport.x -= this.viewportBorder;
  84722. globalViewport.y -= this.viewportBorder;
  84723. globalViewport.width += this.viewportBorder * 2;
  84724. globalViewport.height += this.viewportBorder * 2;
  84725. position.x += this.viewportBorder;
  84726. position.y += this.viewportBorder;
  84727. this._positionX += this.viewportBorder;
  84728. this._positionY += this.viewportBorder;
  84729. }
  84730. if (position.z > 0) {
  84731. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84732. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84733. return true;
  84734. }
  84735. return true;
  84736. }
  84737. return false;
  84738. };
  84739. LensFlareSystem.prototype._isVisible = function () {
  84740. if (!this._isEnabled || !this._scene.activeCamera) {
  84741. return false;
  84742. }
  84743. var emitterPosition = this.getEmitterPosition();
  84744. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84745. var distance = direction.length();
  84746. direction.normalize();
  84747. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84748. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84749. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84750. };
  84751. LensFlareSystem.prototype.render = function () {
  84752. if (!this._effect.isReady() || !this._scene.activeCamera)
  84753. return false;
  84754. var engine = this._scene.getEngine();
  84755. var viewport = this._scene.activeCamera.viewport;
  84756. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84757. // Position
  84758. if (!this.computeEffectivePosition(globalViewport)) {
  84759. return false;
  84760. }
  84761. // Visibility
  84762. if (!this._isVisible()) {
  84763. return false;
  84764. }
  84765. // Intensity
  84766. var awayX;
  84767. var awayY;
  84768. if (this._positionX < this.borderLimit + globalViewport.x) {
  84769. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84770. }
  84771. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84772. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84773. }
  84774. else {
  84775. awayX = 0;
  84776. }
  84777. if (this._positionY < this.borderLimit + globalViewport.y) {
  84778. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84779. }
  84780. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84781. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84782. }
  84783. else {
  84784. awayY = 0;
  84785. }
  84786. var away = (awayX > awayY) ? awayX : awayY;
  84787. away -= this.viewportBorder;
  84788. if (away > this.borderLimit) {
  84789. away = this.borderLimit;
  84790. }
  84791. var intensity = 1.0 - (away / this.borderLimit);
  84792. if (intensity < 0) {
  84793. return false;
  84794. }
  84795. if (intensity > 1.0) {
  84796. intensity = 1.0;
  84797. }
  84798. if (this.viewportBorder > 0) {
  84799. globalViewport.x += this.viewportBorder;
  84800. globalViewport.y += this.viewportBorder;
  84801. globalViewport.width -= this.viewportBorder * 2;
  84802. globalViewport.height -= this.viewportBorder * 2;
  84803. this._positionX -= this.viewportBorder;
  84804. this._positionY -= this.viewportBorder;
  84805. }
  84806. // Position
  84807. var centerX = globalViewport.x + globalViewport.width / 2;
  84808. var centerY = globalViewport.y + globalViewport.height / 2;
  84809. var distX = centerX - this._positionX;
  84810. var distY = centerY - this._positionY;
  84811. // Effects
  84812. engine.enableEffect(this._effect);
  84813. engine.setState(false);
  84814. engine.setDepthBuffer(false);
  84815. // VBOs
  84816. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84817. // Flares
  84818. for (var index = 0; index < this.lensFlares.length; index++) {
  84819. var flare = this.lensFlares[index];
  84820. engine.setAlphaMode(flare.alphaMode);
  84821. var x = centerX - (distX * flare.position);
  84822. var y = centerY - (distY * flare.position);
  84823. var cw = flare.size;
  84824. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84825. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84826. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84827. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84828. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84829. // Texture
  84830. this._effect.setTexture("textureSampler", flare.texture);
  84831. // Color
  84832. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84833. // Draw order
  84834. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84835. }
  84836. engine.setDepthBuffer(true);
  84837. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84838. return true;
  84839. };
  84840. LensFlareSystem.prototype.dispose = function () {
  84841. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84842. if (vertexBuffer) {
  84843. vertexBuffer.dispose();
  84844. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84845. }
  84846. if (this._indexBuffer) {
  84847. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84848. this._indexBuffer = null;
  84849. }
  84850. while (this.lensFlares.length) {
  84851. this.lensFlares[0].dispose();
  84852. }
  84853. // Remove from scene
  84854. var index = this._scene.lensFlareSystems.indexOf(this);
  84855. this._scene.lensFlareSystems.splice(index, 1);
  84856. };
  84857. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84858. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84859. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84860. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84861. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84862. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84863. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84864. var parsedFlare = parsedLensFlareSystem.flares[index];
  84865. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84866. }
  84867. return lensFlareSystem;
  84868. };
  84869. LensFlareSystem.prototype.serialize = function () {
  84870. var serializationObject = {};
  84871. serializationObject.id = this.id;
  84872. serializationObject.name = this.name;
  84873. serializationObject.emitterId = this.getEmitter().id;
  84874. serializationObject.borderLimit = this.borderLimit;
  84875. serializationObject.flares = [];
  84876. for (var index = 0; index < this.lensFlares.length; index++) {
  84877. var flare = this.lensFlares[index];
  84878. serializationObject.flares.push({
  84879. size: flare.size,
  84880. position: flare.position,
  84881. color: flare.color.asArray(),
  84882. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84883. });
  84884. }
  84885. return serializationObject;
  84886. };
  84887. return LensFlareSystem;
  84888. }());
  84889. BABYLON.LensFlareSystem = LensFlareSystem;
  84890. })(BABYLON || (BABYLON = {}));
  84891. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84892. var BABYLON;
  84893. (function (BABYLON) {
  84894. /**
  84895. * This is a holder class for the physics joint created by the physics plugin.
  84896. * It holds a set of functions to control the underlying joint.
  84897. */
  84898. var PhysicsJoint = /** @class */ (function () {
  84899. function PhysicsJoint(type, jointData) {
  84900. this.type = type;
  84901. this.jointData = jointData;
  84902. jointData.nativeParams = jointData.nativeParams || {};
  84903. }
  84904. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84905. get: function () {
  84906. return this._physicsJoint;
  84907. },
  84908. set: function (newJoint) {
  84909. if (this._physicsJoint) {
  84910. //remove from the wolrd
  84911. }
  84912. this._physicsJoint = newJoint;
  84913. },
  84914. enumerable: true,
  84915. configurable: true
  84916. });
  84917. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84918. set: function (physicsPlugin) {
  84919. this._physicsPlugin = physicsPlugin;
  84920. },
  84921. enumerable: true,
  84922. configurable: true
  84923. });
  84924. /**
  84925. * Execute a function that is physics-plugin specific.
  84926. * @param {Function} func the function that will be executed.
  84927. * It accepts two parameters: the physics world and the physics joint.
  84928. */
  84929. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84930. func(this._physicsPlugin.world, this._physicsJoint);
  84931. };
  84932. //TODO check if the native joints are the same
  84933. //Joint Types
  84934. PhysicsJoint.DistanceJoint = 0;
  84935. PhysicsJoint.HingeJoint = 1;
  84936. PhysicsJoint.BallAndSocketJoint = 2;
  84937. PhysicsJoint.WheelJoint = 3;
  84938. PhysicsJoint.SliderJoint = 4;
  84939. //OIMO
  84940. PhysicsJoint.PrismaticJoint = 5;
  84941. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84942. PhysicsJoint.UniversalJoint = 6;
  84943. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84944. //Cannon
  84945. //Similar to a Ball-Joint. Different in params
  84946. PhysicsJoint.PointToPointJoint = 8;
  84947. //Cannon only at the moment
  84948. PhysicsJoint.SpringJoint = 9;
  84949. PhysicsJoint.LockJoint = 10;
  84950. return PhysicsJoint;
  84951. }());
  84952. BABYLON.PhysicsJoint = PhysicsJoint;
  84953. /**
  84954. * A class representing a physics distance joint.
  84955. */
  84956. var DistanceJoint = /** @class */ (function (_super) {
  84957. __extends(DistanceJoint, _super);
  84958. function DistanceJoint(jointData) {
  84959. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84960. }
  84961. /**
  84962. * Update the predefined distance.
  84963. */
  84964. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84965. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84966. };
  84967. return DistanceJoint;
  84968. }(PhysicsJoint));
  84969. BABYLON.DistanceJoint = DistanceJoint;
  84970. var MotorEnabledJoint = /** @class */ (function (_super) {
  84971. __extends(MotorEnabledJoint, _super);
  84972. function MotorEnabledJoint(type, jointData) {
  84973. return _super.call(this, type, jointData) || this;
  84974. }
  84975. /**
  84976. * Set the motor values.
  84977. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84978. * @param {number} force the force to apply
  84979. * @param {number} maxForce max force for this motor.
  84980. */
  84981. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84982. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84983. };
  84984. /**
  84985. * Set the motor's limits.
  84986. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84987. */
  84988. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84989. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84990. };
  84991. return MotorEnabledJoint;
  84992. }(PhysicsJoint));
  84993. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84994. /**
  84995. * This class represents a single hinge physics joint
  84996. */
  84997. var HingeJoint = /** @class */ (function (_super) {
  84998. __extends(HingeJoint, _super);
  84999. function HingeJoint(jointData) {
  85000. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  85001. }
  85002. /**
  85003. * Set the motor values.
  85004. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85005. * @param {number} force the force to apply
  85006. * @param {number} maxForce max force for this motor.
  85007. */
  85008. HingeJoint.prototype.setMotor = function (force, maxForce) {
  85009. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85010. };
  85011. /**
  85012. * Set the motor's limits.
  85013. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85014. */
  85015. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85016. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85017. };
  85018. return HingeJoint;
  85019. }(MotorEnabledJoint));
  85020. BABYLON.HingeJoint = HingeJoint;
  85021. /**
  85022. * This class represents a dual hinge physics joint (same as wheel joint)
  85023. */
  85024. var Hinge2Joint = /** @class */ (function (_super) {
  85025. __extends(Hinge2Joint, _super);
  85026. function Hinge2Joint(jointData) {
  85027. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  85028. }
  85029. /**
  85030. * Set the motor values.
  85031. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85032. * @param {number} force the force to apply
  85033. * @param {number} maxForce max force for this motor.
  85034. * @param {motorIndex} the motor's index, 0 or 1.
  85035. */
  85036. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  85037. if (motorIndex === void 0) { motorIndex = 0; }
  85038. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  85039. };
  85040. /**
  85041. * Set the motor limits.
  85042. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85043. * @param {number} upperLimit the upper limit
  85044. * @param {number} lowerLimit lower limit
  85045. * @param {motorIndex} the motor's index, 0 or 1.
  85046. */
  85047. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  85048. if (motorIndex === void 0) { motorIndex = 0; }
  85049. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  85050. };
  85051. return Hinge2Joint;
  85052. }(MotorEnabledJoint));
  85053. BABYLON.Hinge2Joint = Hinge2Joint;
  85054. })(BABYLON || (BABYLON = {}));
  85055. //# sourceMappingURL=babylon.physicsJoint.js.map
  85056. var BABYLON;
  85057. (function (BABYLON) {
  85058. var PhysicsImpostor = /** @class */ (function () {
  85059. function PhysicsImpostor(object, type, _options, _scene) {
  85060. if (_options === void 0) { _options = { mass: 0 }; }
  85061. var _this = this;
  85062. this.object = object;
  85063. this.type = type;
  85064. this._options = _options;
  85065. this._scene = _scene;
  85066. this._bodyUpdateRequired = false;
  85067. this._onBeforePhysicsStepCallbacks = new Array();
  85068. this._onAfterPhysicsStepCallbacks = new Array();
  85069. this._onPhysicsCollideCallbacks = [];
  85070. this._deltaPosition = BABYLON.Vector3.Zero();
  85071. this._isDisposed = false;
  85072. //temp variables for parent rotation calculations
  85073. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  85074. this._tmpQuat = new BABYLON.Quaternion();
  85075. this._tmpQuat2 = new BABYLON.Quaternion();
  85076. /**
  85077. * this function is executed by the physics engine.
  85078. */
  85079. this.beforeStep = function () {
  85080. if (!_this._physicsEngine) {
  85081. return;
  85082. }
  85083. _this.object.translate(_this._deltaPosition, -1);
  85084. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  85085. _this.object.computeWorldMatrix(false);
  85086. if (_this.object.parent && _this.object.rotationQuaternion) {
  85087. _this.getParentsRotation();
  85088. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  85089. }
  85090. else {
  85091. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  85092. }
  85093. if (!_this._options.disableBidirectionalTransformation) {
  85094. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  85095. }
  85096. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  85097. func(_this);
  85098. });
  85099. };
  85100. /**
  85101. * this function is executed by the physics engine.
  85102. */
  85103. this.afterStep = function () {
  85104. if (!_this._physicsEngine) {
  85105. return;
  85106. }
  85107. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  85108. func(_this);
  85109. });
  85110. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  85111. // object has now its world rotation. needs to be converted to local.
  85112. if (_this.object.parent && _this.object.rotationQuaternion) {
  85113. _this.getParentsRotation();
  85114. _this._tmpQuat.conjugateInPlace();
  85115. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  85116. }
  85117. // take the position set and make it the absolute position of this object.
  85118. _this.object.setAbsolutePosition(_this.object.position);
  85119. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  85120. _this.object.translate(_this._deltaPosition, 1);
  85121. };
  85122. /**
  85123. * Legacy collision detection event support
  85124. */
  85125. this.onCollideEvent = null;
  85126. //event and body object due to cannon's event-based architecture.
  85127. this.onCollide = function (e) {
  85128. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  85129. return;
  85130. }
  85131. if (!_this._physicsEngine) {
  85132. return;
  85133. }
  85134. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  85135. if (otherImpostor) {
  85136. // Legacy collision detection event support
  85137. if (_this.onCollideEvent) {
  85138. _this.onCollideEvent(_this, otherImpostor);
  85139. }
  85140. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  85141. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  85142. }).forEach(function (obj) {
  85143. obj.callback(_this, otherImpostor);
  85144. });
  85145. }
  85146. };
  85147. //sanity check!
  85148. if (!this.object) {
  85149. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  85150. return;
  85151. }
  85152. //legacy support for old syntax.
  85153. if (!this._scene && object.getScene) {
  85154. this._scene = object.getScene();
  85155. }
  85156. if (!this._scene) {
  85157. return;
  85158. }
  85159. this._physicsEngine = this._scene.getPhysicsEngine();
  85160. if (!this._physicsEngine) {
  85161. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  85162. }
  85163. else {
  85164. //set the object's quaternion, if not set
  85165. if (!this.object.rotationQuaternion) {
  85166. if (this.object.rotation) {
  85167. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  85168. }
  85169. else {
  85170. this.object.rotationQuaternion = new BABYLON.Quaternion();
  85171. }
  85172. }
  85173. //default options params
  85174. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  85175. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  85176. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  85177. this._joints = [];
  85178. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  85179. if (!this.object.parent || this._options.ignoreParent) {
  85180. this._init();
  85181. }
  85182. else if (this.object.parent.physicsImpostor) {
  85183. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  85184. }
  85185. }
  85186. }
  85187. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  85188. get: function () {
  85189. return this._isDisposed;
  85190. },
  85191. enumerable: true,
  85192. configurable: true
  85193. });
  85194. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  85195. get: function () {
  85196. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  85197. },
  85198. set: function (value) {
  85199. this.setMass(value);
  85200. },
  85201. enumerable: true,
  85202. configurable: true
  85203. });
  85204. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  85205. get: function () {
  85206. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  85207. },
  85208. set: function (value) {
  85209. if (!this._physicsEngine) {
  85210. return;
  85211. }
  85212. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  85213. },
  85214. enumerable: true,
  85215. configurable: true
  85216. });
  85217. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  85218. get: function () {
  85219. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  85220. },
  85221. set: function (value) {
  85222. if (!this._physicsEngine) {
  85223. return;
  85224. }
  85225. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  85226. },
  85227. enumerable: true,
  85228. configurable: true
  85229. });
  85230. /**
  85231. * This function will completly initialize this impostor.
  85232. * It will create a new body - but only if this mesh has no parent.
  85233. * If it has, this impostor will not be used other than to define the impostor
  85234. * of the child mesh.
  85235. */
  85236. PhysicsImpostor.prototype._init = function () {
  85237. if (!this._physicsEngine) {
  85238. return;
  85239. }
  85240. this._physicsEngine.removeImpostor(this);
  85241. this.physicsBody = null;
  85242. this._parent = this._parent || this._getPhysicsParent();
  85243. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  85244. this._physicsEngine.addImpostor(this);
  85245. }
  85246. };
  85247. PhysicsImpostor.prototype._getPhysicsParent = function () {
  85248. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  85249. var parentMesh = this.object.parent;
  85250. return parentMesh.physicsImpostor;
  85251. }
  85252. return null;
  85253. };
  85254. /**
  85255. * Should a new body be generated.
  85256. */
  85257. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  85258. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  85259. };
  85260. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  85261. this.forceUpdate();
  85262. };
  85263. /**
  85264. * Force a regeneration of this or the parent's impostor's body.
  85265. * Use under cautious - This will remove all joints already implemented.
  85266. */
  85267. PhysicsImpostor.prototype.forceUpdate = function () {
  85268. this._init();
  85269. if (this.parent && !this._options.ignoreParent) {
  85270. this.parent.forceUpdate();
  85271. }
  85272. };
  85273. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  85274. /*public get mesh(): AbstractMesh {
  85275. return this._mesh;
  85276. }*/
  85277. /**
  85278. * Gets the body that holds this impostor. Either its own, or its parent.
  85279. */
  85280. get: function () {
  85281. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  85282. },
  85283. /**
  85284. * Set the physics body. Used mainly by the physics engine/plugin
  85285. */
  85286. set: function (physicsBody) {
  85287. if (this._physicsBody && this._physicsEngine) {
  85288. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  85289. }
  85290. this._physicsBody = physicsBody;
  85291. this.resetUpdateFlags();
  85292. },
  85293. enumerable: true,
  85294. configurable: true
  85295. });
  85296. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  85297. get: function () {
  85298. return !this._options.ignoreParent && this._parent ? this._parent : null;
  85299. },
  85300. set: function (value) {
  85301. this._parent = value;
  85302. },
  85303. enumerable: true,
  85304. configurable: true
  85305. });
  85306. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85307. this._bodyUpdateRequired = false;
  85308. };
  85309. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85310. if (this.object.getBoundingInfo) {
  85311. var q = this.object.rotationQuaternion;
  85312. //reset rotation
  85313. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85314. //calculate the world matrix with no rotation
  85315. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85316. var boundingInfo = this.object.getBoundingInfo();
  85317. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85318. //bring back the rotation
  85319. this.object.rotationQuaternion = q;
  85320. //calculate the world matrix with the new rotation
  85321. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85322. return size;
  85323. }
  85324. else {
  85325. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85326. }
  85327. };
  85328. PhysicsImpostor.prototype.getObjectCenter = function () {
  85329. if (this.object.getBoundingInfo) {
  85330. var boundingInfo = this.object.getBoundingInfo();
  85331. return boundingInfo.boundingBox.centerWorld;
  85332. }
  85333. else {
  85334. return this.object.position;
  85335. }
  85336. };
  85337. /**
  85338. * Get a specific parametes from the options parameter.
  85339. */
  85340. PhysicsImpostor.prototype.getParam = function (paramName) {
  85341. return this._options[paramName];
  85342. };
  85343. /**
  85344. * Sets a specific parameter in the options given to the physics plugin
  85345. */
  85346. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85347. this._options[paramName] = value;
  85348. this._bodyUpdateRequired = true;
  85349. };
  85350. /**
  85351. * Specifically change the body's mass option. Won't recreate the physics body object
  85352. */
  85353. PhysicsImpostor.prototype.setMass = function (mass) {
  85354. if (this.getParam("mass") !== mass) {
  85355. this.setParam("mass", mass);
  85356. }
  85357. if (this._physicsEngine) {
  85358. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85359. }
  85360. };
  85361. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85362. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85363. };
  85364. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85365. if (this._physicsEngine) {
  85366. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85367. }
  85368. };
  85369. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85370. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85371. };
  85372. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85373. if (this._physicsEngine) {
  85374. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85375. }
  85376. };
  85377. /**
  85378. * Execute a function with the physics plugin native code.
  85379. * Provide a function the will have two variables - the world object and the physics body object.
  85380. */
  85381. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85382. if (this._physicsEngine) {
  85383. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85384. }
  85385. };
  85386. /**
  85387. * Register a function that will be executed before the physics world is stepping forward.
  85388. */
  85389. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85390. this._onBeforePhysicsStepCallbacks.push(func);
  85391. };
  85392. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85393. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85394. if (index > -1) {
  85395. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85396. }
  85397. else {
  85398. BABYLON.Tools.Warn("Function to remove was not found");
  85399. }
  85400. };
  85401. /**
  85402. * Register a function that will be executed after the physics step
  85403. */
  85404. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85405. this._onAfterPhysicsStepCallbacks.push(func);
  85406. };
  85407. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85408. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85409. if (index > -1) {
  85410. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85411. }
  85412. else {
  85413. BABYLON.Tools.Warn("Function to remove was not found");
  85414. }
  85415. };
  85416. /**
  85417. * register a function that will be executed when this impostor collides against a different body.
  85418. */
  85419. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85420. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85421. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85422. };
  85423. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85424. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85425. var index = -1;
  85426. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85427. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85428. // chcek the arrays match
  85429. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85430. return collidedAgainstList.indexOf(impostor) > -1;
  85431. });
  85432. if (sameList) {
  85433. index = idx;
  85434. }
  85435. return sameList;
  85436. }
  85437. return false;
  85438. });
  85439. if (found) {
  85440. this._onPhysicsCollideCallbacks.splice(index, 1);
  85441. }
  85442. else {
  85443. BABYLON.Tools.Warn("Function to remove was not found");
  85444. }
  85445. };
  85446. PhysicsImpostor.prototype.getParentsRotation = function () {
  85447. var parent = this.object.parent;
  85448. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85449. while (parent) {
  85450. if (parent.rotationQuaternion) {
  85451. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85452. }
  85453. else {
  85454. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85455. }
  85456. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85457. parent = parent.parent;
  85458. }
  85459. return this._tmpQuat;
  85460. };
  85461. /**
  85462. * Apply a force
  85463. */
  85464. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85465. if (this._physicsEngine) {
  85466. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85467. }
  85468. return this;
  85469. };
  85470. /**
  85471. * Apply an impulse
  85472. */
  85473. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85474. if (this._physicsEngine) {
  85475. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85476. }
  85477. return this;
  85478. };
  85479. /**
  85480. * A help function to create a joint.
  85481. */
  85482. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85483. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85484. this.addJoint(otherImpostor, joint);
  85485. return this;
  85486. };
  85487. /**
  85488. * Add a joint to this impostor with a different impostor.
  85489. */
  85490. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85491. this._joints.push({
  85492. otherImpostor: otherImpostor,
  85493. joint: joint
  85494. });
  85495. if (this._physicsEngine) {
  85496. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85497. }
  85498. return this;
  85499. };
  85500. /**
  85501. * Will keep this body still, in a sleep mode.
  85502. */
  85503. PhysicsImpostor.prototype.sleep = function () {
  85504. if (this._physicsEngine) {
  85505. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85506. }
  85507. return this;
  85508. };
  85509. /**
  85510. * Wake the body up.
  85511. */
  85512. PhysicsImpostor.prototype.wakeUp = function () {
  85513. if (this._physicsEngine) {
  85514. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85515. }
  85516. return this;
  85517. };
  85518. PhysicsImpostor.prototype.clone = function (newObject) {
  85519. if (!newObject)
  85520. return null;
  85521. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85522. };
  85523. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85524. var _this = this;
  85525. //no dispose if no physics engine is available.
  85526. if (!this._physicsEngine) {
  85527. return;
  85528. }
  85529. this._joints.forEach(function (j) {
  85530. if (_this._physicsEngine) {
  85531. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85532. }
  85533. });
  85534. //dispose the physics body
  85535. this._physicsEngine.removeImpostor(this);
  85536. if (this.parent) {
  85537. this.parent.forceUpdate();
  85538. }
  85539. else {
  85540. /*this._object.getChildMeshes().forEach(function(mesh) {
  85541. if (mesh.physicsImpostor) {
  85542. if (disposeChildren) {
  85543. mesh.physicsImpostor.dispose();
  85544. mesh.physicsImpostor = null;
  85545. }
  85546. }
  85547. })*/
  85548. }
  85549. this._isDisposed = true;
  85550. };
  85551. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85552. this._deltaPosition.copyFrom(position);
  85553. };
  85554. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85555. if (!this._deltaRotation) {
  85556. this._deltaRotation = new BABYLON.Quaternion();
  85557. }
  85558. this._deltaRotation.copyFrom(rotation);
  85559. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85560. };
  85561. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85562. if (this._physicsEngine) {
  85563. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85564. }
  85565. return this;
  85566. };
  85567. PhysicsImpostor.prototype.getRadius = function () {
  85568. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85569. };
  85570. /**
  85571. * Sync a bone with this impostor
  85572. * @param bone The bone to sync to the impostor.
  85573. * @param boneMesh The mesh that the bone is influencing.
  85574. * @param jointPivot The pivot of the joint / bone in local space.
  85575. * @param distToJoint Optional distance from the impostor to the joint.
  85576. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85577. */
  85578. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85579. var tempVec = PhysicsImpostor._tmpVecs[0];
  85580. var mesh = this.object;
  85581. if (mesh.rotationQuaternion) {
  85582. if (adjustRotation) {
  85583. var tempQuat = PhysicsImpostor._tmpQuat;
  85584. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85585. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85586. }
  85587. else {
  85588. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85589. }
  85590. }
  85591. tempVec.x = 0;
  85592. tempVec.y = 0;
  85593. tempVec.z = 0;
  85594. if (jointPivot) {
  85595. tempVec.x = jointPivot.x;
  85596. tempVec.y = jointPivot.y;
  85597. tempVec.z = jointPivot.z;
  85598. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85599. if (distToJoint === undefined || distToJoint === null) {
  85600. distToJoint = jointPivot.length();
  85601. }
  85602. tempVec.x *= distToJoint;
  85603. tempVec.y *= distToJoint;
  85604. tempVec.z *= distToJoint;
  85605. }
  85606. if (bone.getParent()) {
  85607. tempVec.addInPlace(mesh.getAbsolutePosition());
  85608. bone.setAbsolutePosition(tempVec, boneMesh);
  85609. }
  85610. else {
  85611. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85612. boneMesh.position.x -= tempVec.x;
  85613. boneMesh.position.y -= tempVec.y;
  85614. boneMesh.position.z -= tempVec.z;
  85615. }
  85616. };
  85617. /**
  85618. * Sync impostor to a bone
  85619. * @param bone The bone that the impostor will be synced to.
  85620. * @param boneMesh The mesh that the bone is influencing.
  85621. * @param jointPivot The pivot of the joint / bone in local space.
  85622. * @param distToJoint Optional distance from the impostor to the joint.
  85623. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85624. * @param boneAxis Optional vector3 axis the bone is aligned with
  85625. */
  85626. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85627. var mesh = this.object;
  85628. if (mesh.rotationQuaternion) {
  85629. if (adjustRotation) {
  85630. var tempQuat = PhysicsImpostor._tmpQuat;
  85631. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85632. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85633. }
  85634. else {
  85635. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85636. }
  85637. }
  85638. var pos = PhysicsImpostor._tmpVecs[0];
  85639. var boneDir = PhysicsImpostor._tmpVecs[1];
  85640. if (!boneAxis) {
  85641. boneAxis = PhysicsImpostor._tmpVecs[2];
  85642. boneAxis.x = 0;
  85643. boneAxis.y = 1;
  85644. boneAxis.z = 0;
  85645. }
  85646. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85647. bone.getAbsolutePositionToRef(boneMesh, pos);
  85648. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85649. distToJoint = jointPivot.length();
  85650. }
  85651. if (distToJoint !== undefined && distToJoint !== null) {
  85652. pos.x += boneDir.x * distToJoint;
  85653. pos.y += boneDir.y * distToJoint;
  85654. pos.z += boneDir.z * distToJoint;
  85655. }
  85656. mesh.setAbsolutePosition(pos);
  85657. };
  85658. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85659. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85660. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85661. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85662. //Impostor types
  85663. PhysicsImpostor.NoImpostor = 0;
  85664. PhysicsImpostor.SphereImpostor = 1;
  85665. PhysicsImpostor.BoxImpostor = 2;
  85666. PhysicsImpostor.PlaneImpostor = 3;
  85667. PhysicsImpostor.MeshImpostor = 4;
  85668. PhysicsImpostor.CylinderImpostor = 7;
  85669. PhysicsImpostor.ParticleImpostor = 8;
  85670. PhysicsImpostor.HeightmapImpostor = 9;
  85671. return PhysicsImpostor;
  85672. }());
  85673. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85674. })(BABYLON || (BABYLON = {}));
  85675. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85676. var BABYLON;
  85677. (function (BABYLON) {
  85678. var PhysicsEngine = /** @class */ (function () {
  85679. function PhysicsEngine(gravity, _physicsPlugin) {
  85680. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85681. this._physicsPlugin = _physicsPlugin;
  85682. //new methods and parameters
  85683. this._impostors = [];
  85684. this._joints = [];
  85685. if (!this._physicsPlugin.isSupported()) {
  85686. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85687. + "Please make sure it is included.");
  85688. }
  85689. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85690. this.setGravity(gravity);
  85691. this.setTimeStep();
  85692. }
  85693. PhysicsEngine.prototype.setGravity = function (gravity) {
  85694. this.gravity = gravity;
  85695. this._physicsPlugin.setGravity(this.gravity);
  85696. };
  85697. /**
  85698. * Set the time step of the physics engine.
  85699. * default is 1/60.
  85700. * To slow it down, enter 1/600 for example.
  85701. * To speed it up, 1/30
  85702. * @param {number} newTimeStep the new timestep to apply to this world.
  85703. */
  85704. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85705. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85706. this._physicsPlugin.setTimeStep(newTimeStep);
  85707. };
  85708. /**
  85709. * Get the time step of the physics engine.
  85710. */
  85711. PhysicsEngine.prototype.getTimeStep = function () {
  85712. return this._physicsPlugin.getTimeStep();
  85713. };
  85714. PhysicsEngine.prototype.dispose = function () {
  85715. this._impostors.forEach(function (impostor) {
  85716. impostor.dispose();
  85717. });
  85718. this._physicsPlugin.dispose();
  85719. };
  85720. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85721. return this._physicsPlugin.name;
  85722. };
  85723. /**
  85724. * Adding a new impostor for the impostor tracking.
  85725. * This will be done by the impostor itself.
  85726. * @param {PhysicsImpostor} impostor the impostor to add
  85727. */
  85728. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85729. impostor.uniqueId = this._impostors.push(impostor);
  85730. //if no parent, generate the body
  85731. if (!impostor.parent) {
  85732. this._physicsPlugin.generatePhysicsBody(impostor);
  85733. }
  85734. };
  85735. /**
  85736. * Remove an impostor from the engine.
  85737. * This impostor and its mesh will not longer be updated by the physics engine.
  85738. * @param {PhysicsImpostor} impostor the impostor to remove
  85739. */
  85740. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85741. var index = this._impostors.indexOf(impostor);
  85742. if (index > -1) {
  85743. var removed = this._impostors.splice(index, 1);
  85744. //Is it needed?
  85745. if (removed.length) {
  85746. //this will also remove it from the world.
  85747. removed[0].physicsBody = null;
  85748. }
  85749. }
  85750. };
  85751. /**
  85752. * Add a joint to the physics engine
  85753. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85754. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85755. * @param {PhysicsJoint} the joint that will connect both impostors.
  85756. */
  85757. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85758. var impostorJoint = {
  85759. mainImpostor: mainImpostor,
  85760. connectedImpostor: connectedImpostor,
  85761. joint: joint
  85762. };
  85763. joint.physicsPlugin = this._physicsPlugin;
  85764. this._joints.push(impostorJoint);
  85765. this._physicsPlugin.generateJoint(impostorJoint);
  85766. };
  85767. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85768. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85769. return (impostorJoint.connectedImpostor === connectedImpostor
  85770. && impostorJoint.joint === joint
  85771. && impostorJoint.mainImpostor === mainImpostor);
  85772. });
  85773. if (matchingJoints.length) {
  85774. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85775. //TODO remove it from the list as well
  85776. }
  85777. };
  85778. /**
  85779. * Called by the scene. no need to call it.
  85780. */
  85781. PhysicsEngine.prototype._step = function (delta) {
  85782. var _this = this;
  85783. //check if any mesh has no body / requires an update
  85784. this._impostors.forEach(function (impostor) {
  85785. if (impostor.isBodyInitRequired()) {
  85786. _this._physicsPlugin.generatePhysicsBody(impostor);
  85787. }
  85788. });
  85789. if (delta > 0.1) {
  85790. delta = 0.1;
  85791. }
  85792. else if (delta <= 0) {
  85793. delta = 1.0 / 60.0;
  85794. }
  85795. this._physicsPlugin.executeStep(delta, this._impostors);
  85796. };
  85797. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85798. return this._physicsPlugin;
  85799. };
  85800. PhysicsEngine.prototype.getImpostors = function () {
  85801. return this._impostors;
  85802. };
  85803. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85804. for (var i = 0; i < this._impostors.length; ++i) {
  85805. if (this._impostors[i].object === object) {
  85806. return this._impostors[i];
  85807. }
  85808. }
  85809. return null;
  85810. };
  85811. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85812. for (var i = 0; i < this._impostors.length; ++i) {
  85813. if (this._impostors[i].physicsBody === body) {
  85814. return this._impostors[i];
  85815. }
  85816. }
  85817. return null;
  85818. };
  85819. // Statics
  85820. PhysicsEngine.Epsilon = 0.001;
  85821. return PhysicsEngine;
  85822. }());
  85823. BABYLON.PhysicsEngine = PhysicsEngine;
  85824. })(BABYLON || (BABYLON = {}));
  85825. //# sourceMappingURL=babylon.physicsEngine.js.map
  85826. var BABYLON;
  85827. (function (BABYLON) {
  85828. var PhysicsHelper = /** @class */ (function () {
  85829. function PhysicsHelper(scene) {
  85830. this._scene = scene;
  85831. this._physicsEngine = this._scene.getPhysicsEngine();
  85832. if (!this._physicsEngine) {
  85833. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85834. }
  85835. }
  85836. /**
  85837. * @param {Vector3} origin the origin of the explosion
  85838. * @param {number} radius the explosion radius
  85839. * @param {number} strength the explosion strength
  85840. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85841. */
  85842. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85843. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85844. if (!this._physicsEngine) {
  85845. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85846. return null;
  85847. }
  85848. var impostors = this._physicsEngine.getImpostors();
  85849. if (impostors.length === 0) {
  85850. return null;
  85851. }
  85852. var event = new PhysicsRadialExplosionEvent(this._scene);
  85853. impostors.forEach(function (impostor) {
  85854. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85855. if (!impostorForceAndContactPoint) {
  85856. return;
  85857. }
  85858. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85859. });
  85860. event.dispose(false);
  85861. return event;
  85862. };
  85863. /**
  85864. * @param {Vector3} origin the origin of the explosion
  85865. * @param {number} radius the explosion radius
  85866. * @param {number} strength the explosion strength
  85867. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85868. */
  85869. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85870. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85871. if (!this._physicsEngine) {
  85872. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85873. return null;
  85874. }
  85875. var impostors = this._physicsEngine.getImpostors();
  85876. if (impostors.length === 0) {
  85877. return null;
  85878. }
  85879. var event = new PhysicsRadialExplosionEvent(this._scene);
  85880. impostors.forEach(function (impostor) {
  85881. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85882. if (!impostorForceAndContactPoint) {
  85883. return;
  85884. }
  85885. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85886. });
  85887. event.dispose(false);
  85888. return event;
  85889. };
  85890. /**
  85891. * @param {Vector3} origin the origin of the explosion
  85892. * @param {number} radius the explosion radius
  85893. * @param {number} strength the explosion strength
  85894. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85895. */
  85896. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85897. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85898. if (!this._physicsEngine) {
  85899. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85900. return null;
  85901. }
  85902. var impostors = this._physicsEngine.getImpostors();
  85903. if (impostors.length === 0) {
  85904. return null;
  85905. }
  85906. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85907. event.dispose(false);
  85908. return event;
  85909. };
  85910. /**
  85911. * @param {Vector3} origin the origin of the updraft
  85912. * @param {number} radius the radius of the updraft
  85913. * @param {number} strength the strength of the updraft
  85914. * @param {number} height the height of the updraft
  85915. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85916. */
  85917. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85918. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85919. if (!this._physicsEngine) {
  85920. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85921. return null;
  85922. }
  85923. if (this._physicsEngine.getImpostors().length === 0) {
  85924. return null;
  85925. }
  85926. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85927. event.dispose(false);
  85928. return event;
  85929. };
  85930. /**
  85931. * @param {Vector3} origin the of the vortex
  85932. * @param {number} radius the radius of the vortex
  85933. * @param {number} strength the strength of the vortex
  85934. * @param {number} height the height of the vortex
  85935. */
  85936. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85937. if (!this._physicsEngine) {
  85938. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85939. return null;
  85940. }
  85941. if (this._physicsEngine.getImpostors().length === 0) {
  85942. return null;
  85943. }
  85944. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85945. event.dispose(false);
  85946. return event;
  85947. };
  85948. return PhysicsHelper;
  85949. }());
  85950. BABYLON.PhysicsHelper = PhysicsHelper;
  85951. /***** Radial explosion *****/
  85952. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85953. function PhysicsRadialExplosionEvent(scene) {
  85954. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85955. this._rays = [];
  85956. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85957. this._scene = scene;
  85958. }
  85959. /**
  85960. * Returns the data related to the radial explosion event (sphere & rays).
  85961. * @returns {PhysicsRadialExplosionEventData}
  85962. */
  85963. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85964. this._dataFetched = true;
  85965. return {
  85966. sphere: this._sphere,
  85967. rays: this._rays,
  85968. };
  85969. };
  85970. /**
  85971. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85972. * @param impostor
  85973. * @param {Vector3} origin the origin of the explosion
  85974. * @param {number} radius the explosion radius
  85975. * @param {number} strength the explosion strength
  85976. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85977. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85978. */
  85979. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85980. if (impostor.mass === 0) {
  85981. return null;
  85982. }
  85983. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85984. return null;
  85985. }
  85986. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85987. return null;
  85988. }
  85989. var impostorObjectCenter = impostor.getObjectCenter();
  85990. var direction = impostorObjectCenter.subtract(origin);
  85991. var ray = new BABYLON.Ray(origin, direction, radius);
  85992. this._rays.push(ray);
  85993. var hit = ray.intersectsMesh(impostor.object);
  85994. var contactPoint = hit.pickedPoint;
  85995. if (!contactPoint) {
  85996. return null;
  85997. }
  85998. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85999. if (distanceFromOrigin > radius) {
  86000. return null;
  86001. }
  86002. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  86003. ? strength
  86004. : strength * (1 - (distanceFromOrigin / radius));
  86005. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86006. return { force: force, contactPoint: contactPoint };
  86007. };
  86008. /**
  86009. * Disposes the sphere.
  86010. * @param {bolean} force
  86011. */
  86012. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  86013. var _this = this;
  86014. if (force === void 0) { force = true; }
  86015. if (force) {
  86016. this._sphere.dispose();
  86017. }
  86018. else {
  86019. setTimeout(function () {
  86020. if (!_this._dataFetched) {
  86021. _this._sphere.dispose();
  86022. }
  86023. }, 0);
  86024. }
  86025. };
  86026. /*** Helpers ***/
  86027. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  86028. if (!this._sphere) {
  86029. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  86030. this._sphere.isVisible = false;
  86031. }
  86032. };
  86033. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  86034. var impostorObject = impostor.object;
  86035. this._prepareSphere();
  86036. this._sphere.position = origin;
  86037. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  86038. this._sphere._updateBoundingInfo();
  86039. this._sphere.computeWorldMatrix(true);
  86040. return this._sphere.intersectsMesh(impostorObject, true);
  86041. };
  86042. return PhysicsRadialExplosionEvent;
  86043. }());
  86044. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  86045. /***** Gravitational Field *****/
  86046. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  86047. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  86048. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86049. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86050. this._physicsHelper = physicsHelper;
  86051. this._scene = scene;
  86052. this._origin = origin;
  86053. this._radius = radius;
  86054. this._strength = strength;
  86055. this._falloff = falloff;
  86056. this._tickCallback = this._tick.bind(this);
  86057. }
  86058. /**
  86059. * Returns the data related to the gravitational field event (sphere).
  86060. * @returns {PhysicsGravitationalFieldEventData}
  86061. */
  86062. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  86063. this._dataFetched = true;
  86064. return {
  86065. sphere: this._sphere,
  86066. };
  86067. };
  86068. /**
  86069. * Enables the gravitational field.
  86070. */
  86071. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  86072. this._tickCallback.call(this);
  86073. this._scene.registerBeforeRender(this._tickCallback);
  86074. };
  86075. /**
  86076. * Disables the gravitational field.
  86077. */
  86078. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  86079. this._scene.unregisterBeforeRender(this._tickCallback);
  86080. };
  86081. /**
  86082. * Disposes the sphere.
  86083. * @param {bolean} force
  86084. */
  86085. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  86086. var _this = this;
  86087. if (force === void 0) { force = true; }
  86088. if (force) {
  86089. this._sphere.dispose();
  86090. }
  86091. else {
  86092. setTimeout(function () {
  86093. if (!_this._dataFetched) {
  86094. _this._sphere.dispose();
  86095. }
  86096. }, 0);
  86097. }
  86098. };
  86099. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  86100. // Since the params won't change, we fetch the event only once
  86101. if (this._sphere) {
  86102. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86103. }
  86104. else {
  86105. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86106. if (radialExplosionEvent) {
  86107. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  86108. }
  86109. }
  86110. };
  86111. return PhysicsGravitationalFieldEvent;
  86112. }());
  86113. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  86114. /***** Updraft *****/
  86115. var PhysicsUpdraftEvent = /** @class */ (function () {
  86116. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  86117. this._scene = _scene;
  86118. this._origin = _origin;
  86119. this._radius = _radius;
  86120. this._strength = _strength;
  86121. this._height = _height;
  86122. this._updraftMode = _updraftMode;
  86123. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86124. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  86125. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86126. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86127. this._physicsEngine = this._scene.getPhysicsEngine();
  86128. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86129. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86130. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86131. this._originDirection = this._origin.subtract(this._originTop).normalize();
  86132. }
  86133. this._tickCallback = this._tick.bind(this);
  86134. }
  86135. /**
  86136. * Returns the data related to the updraft event (cylinder).
  86137. * @returns {PhysicsUpdraftEventData}
  86138. */
  86139. PhysicsUpdraftEvent.prototype.getData = function () {
  86140. this._dataFetched = true;
  86141. return {
  86142. cylinder: this._cylinder,
  86143. };
  86144. };
  86145. /**
  86146. * Enables the updraft.
  86147. */
  86148. PhysicsUpdraftEvent.prototype.enable = function () {
  86149. this._tickCallback.call(this);
  86150. this._scene.registerBeforeRender(this._tickCallback);
  86151. };
  86152. /**
  86153. * Disables the cortex.
  86154. */
  86155. PhysicsUpdraftEvent.prototype.disable = function () {
  86156. this._scene.unregisterBeforeRender(this._tickCallback);
  86157. };
  86158. /**
  86159. * Disposes the sphere.
  86160. * @param {bolean} force
  86161. */
  86162. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  86163. var _this = this;
  86164. if (force === void 0) { force = true; }
  86165. if (force) {
  86166. this._cylinder.dispose();
  86167. }
  86168. else {
  86169. setTimeout(function () {
  86170. if (!_this._dataFetched) {
  86171. _this._cylinder.dispose();
  86172. }
  86173. }, 0);
  86174. }
  86175. };
  86176. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86177. if (impostor.mass === 0) {
  86178. return null;
  86179. }
  86180. if (!this._intersectsWithCylinder(impostor)) {
  86181. return null;
  86182. }
  86183. var impostorObjectCenter = impostor.getObjectCenter();
  86184. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86185. var direction = this._originDirection;
  86186. }
  86187. else {
  86188. var direction = impostorObjectCenter.subtract(this._originTop);
  86189. }
  86190. var multiplier = this._strength * -1;
  86191. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86192. return { force: force, contactPoint: impostorObjectCenter };
  86193. };
  86194. PhysicsUpdraftEvent.prototype._tick = function () {
  86195. var _this = this;
  86196. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86197. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86198. if (!impostorForceAndContactPoint) {
  86199. return;
  86200. }
  86201. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86202. });
  86203. };
  86204. /*** Helpers ***/
  86205. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  86206. if (!this._cylinder) {
  86207. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  86208. height: this._height,
  86209. diameter: this._radius * 2,
  86210. }, this._scene);
  86211. this._cylinder.isVisible = false;
  86212. }
  86213. };
  86214. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  86215. var impostorObject = impostor.object;
  86216. this._prepareCylinder();
  86217. this._cylinder.position = this._cylinderPosition;
  86218. return this._cylinder.intersectsMesh(impostorObject, true);
  86219. };
  86220. return PhysicsUpdraftEvent;
  86221. }());
  86222. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  86223. /***** Vortex *****/
  86224. var PhysicsVortexEvent = /** @class */ (function () {
  86225. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  86226. this._scene = _scene;
  86227. this._origin = _origin;
  86228. this._radius = _radius;
  86229. this._strength = _strength;
  86230. this._height = _height;
  86231. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86232. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  86233. this._updraftMultiplier = 0.02;
  86234. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86235. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86236. this._physicsEngine = this._scene.getPhysicsEngine();
  86237. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86238. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86239. this._tickCallback = this._tick.bind(this);
  86240. }
  86241. /**
  86242. * Returns the data related to the vortex event (cylinder).
  86243. * @returns {PhysicsVortexEventData}
  86244. */
  86245. PhysicsVortexEvent.prototype.getData = function () {
  86246. this._dataFetched = true;
  86247. return {
  86248. cylinder: this._cylinder,
  86249. };
  86250. };
  86251. /**
  86252. * Enables the vortex.
  86253. */
  86254. PhysicsVortexEvent.prototype.enable = function () {
  86255. this._tickCallback.call(this);
  86256. this._scene.registerBeforeRender(this._tickCallback);
  86257. };
  86258. /**
  86259. * Disables the cortex.
  86260. */
  86261. PhysicsVortexEvent.prototype.disable = function () {
  86262. this._scene.unregisterBeforeRender(this._tickCallback);
  86263. };
  86264. /**
  86265. * Disposes the sphere.
  86266. * @param {bolean} force
  86267. */
  86268. PhysicsVortexEvent.prototype.dispose = function (force) {
  86269. var _this = this;
  86270. if (force === void 0) { force = true; }
  86271. if (force) {
  86272. this._cylinder.dispose();
  86273. }
  86274. else {
  86275. setTimeout(function () {
  86276. if (!_this._dataFetched) {
  86277. _this._cylinder.dispose();
  86278. }
  86279. }, 0);
  86280. }
  86281. };
  86282. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86283. if (impostor.mass === 0) {
  86284. return null;
  86285. }
  86286. if (!this._intersectsWithCylinder(impostor)) {
  86287. return null;
  86288. }
  86289. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86290. return null;
  86291. }
  86292. var impostorObjectCenter = impostor.getObjectCenter();
  86293. 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)
  86294. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  86295. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  86296. var hit = ray.intersectsMesh(impostor.object);
  86297. var contactPoint = hit.pickedPoint;
  86298. if (!contactPoint) {
  86299. return null;
  86300. }
  86301. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86302. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86303. var directionToOrigin = contactPoint.normalize();
  86304. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86305. directionToOrigin = directionToOrigin.negate();
  86306. }
  86307. // TODO: find a more physically based solution
  86308. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86309. var forceX = directionToOrigin.x * this._strength / 8;
  86310. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86311. var forceZ = directionToOrigin.z * this._strength / 8;
  86312. }
  86313. else {
  86314. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86315. var forceY = this._originTop.y * this._updraftMultiplier;
  86316. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86317. }
  86318. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86319. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86320. return { force: force, contactPoint: impostorObjectCenter };
  86321. };
  86322. PhysicsVortexEvent.prototype._tick = function () {
  86323. var _this = this;
  86324. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86325. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86326. if (!impostorForceAndContactPoint) {
  86327. return;
  86328. }
  86329. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86330. });
  86331. };
  86332. /*** Helpers ***/
  86333. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86334. if (!this._cylinder) {
  86335. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86336. height: this._height,
  86337. diameter: this._radius * 2,
  86338. }, this._scene);
  86339. this._cylinder.isVisible = false;
  86340. }
  86341. };
  86342. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86343. var impostorObject = impostor.object;
  86344. this._prepareCylinder();
  86345. this._cylinder.position = this._cylinderPosition;
  86346. return this._cylinder.intersectsMesh(impostorObject, true);
  86347. };
  86348. return PhysicsVortexEvent;
  86349. }());
  86350. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86351. /***** Enums *****/
  86352. /**
  86353. * The strenght of the force in correspondence to the distance of the affected object
  86354. */
  86355. var PhysicsRadialImpulseFalloff;
  86356. (function (PhysicsRadialImpulseFalloff) {
  86357. /** Defines that impulse is constant in strength across it's whole radius */
  86358. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86359. /** DEfines that impulse gets weaker if it's further from the origin */
  86360. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86361. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86362. /**
  86363. * The strenght of the force in correspondence to the distance of the affected object
  86364. */
  86365. var PhysicsUpdraftMode;
  86366. (function (PhysicsUpdraftMode) {
  86367. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86368. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86369. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86370. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86371. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86372. })(BABYLON || (BABYLON = {}));
  86373. //# sourceMappingURL=babylon.physicsHelper.js.map
  86374. var BABYLON;
  86375. (function (BABYLON) {
  86376. var CannonJSPlugin = /** @class */ (function () {
  86377. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86378. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86379. if (iterations === void 0) { iterations = 10; }
  86380. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86381. this.name = "CannonJSPlugin";
  86382. this._physicsMaterials = new Array();
  86383. this._fixedTimeStep = 1 / 60;
  86384. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86385. this.BJSCANNON = CANNON;
  86386. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86387. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86388. this._tmpPosition = BABYLON.Vector3.Zero();
  86389. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86390. this._tmpUnityRotation = new BABYLON.Quaternion();
  86391. if (!this.isSupported()) {
  86392. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86393. return;
  86394. }
  86395. this._extendNamespace();
  86396. this.world = new this.BJSCANNON.World();
  86397. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86398. this.world.solver.iterations = iterations;
  86399. }
  86400. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86401. this.world.gravity.copy(gravity);
  86402. };
  86403. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86404. this._fixedTimeStep = timeStep;
  86405. };
  86406. CannonJSPlugin.prototype.getTimeStep = function () {
  86407. return this._fixedTimeStep;
  86408. };
  86409. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86410. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86411. };
  86412. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86413. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86414. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86415. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86416. };
  86417. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86418. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86419. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86420. impostor.physicsBody.applyForce(impulse, worldPoint);
  86421. };
  86422. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86423. //parent-child relationship. Does this impostor has a parent impostor?
  86424. if (impostor.parent) {
  86425. if (impostor.physicsBody) {
  86426. this.removePhysicsBody(impostor);
  86427. //TODO is that needed?
  86428. impostor.forceUpdate();
  86429. }
  86430. return;
  86431. }
  86432. //should a new body be created for this impostor?
  86433. if (impostor.isBodyInitRequired()) {
  86434. var shape = this._createShape(impostor);
  86435. //unregister events, if body is being changed
  86436. var oldBody = impostor.physicsBody;
  86437. if (oldBody) {
  86438. this.removePhysicsBody(impostor);
  86439. }
  86440. //create the body and material
  86441. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86442. var bodyCreationObject = {
  86443. mass: impostor.getParam("mass"),
  86444. material: material
  86445. };
  86446. // A simple extend, in case native options were used.
  86447. var nativeOptions = impostor.getParam("nativeOptions");
  86448. for (var key in nativeOptions) {
  86449. if (nativeOptions.hasOwnProperty(key)) {
  86450. bodyCreationObject[key] = nativeOptions[key];
  86451. }
  86452. }
  86453. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86454. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86455. this.world.addEventListener("preStep", impostor.beforeStep);
  86456. this.world.addEventListener("postStep", impostor.afterStep);
  86457. impostor.physicsBody.addShape(shape);
  86458. this.world.add(impostor.physicsBody);
  86459. //try to keep the body moving in the right direction by taking old properties.
  86460. //Should be tested!
  86461. if (oldBody) {
  86462. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86463. impostor.physicsBody[param].copy(oldBody[param]);
  86464. });
  86465. }
  86466. this._processChildMeshes(impostor);
  86467. }
  86468. //now update the body's transformation
  86469. this._updatePhysicsBodyTransformation(impostor);
  86470. };
  86471. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86472. var _this = this;
  86473. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86474. var currentRotation = mainImpostor.object.rotationQuaternion;
  86475. if (meshChildren.length) {
  86476. var processMesh = function (localPosition, mesh) {
  86477. if (!currentRotation || !mesh.rotationQuaternion) {
  86478. return;
  86479. }
  86480. var childImpostor = mesh.getPhysicsImpostor();
  86481. if (childImpostor) {
  86482. var parent = childImpostor.parent;
  86483. if (parent !== mainImpostor) {
  86484. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86485. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86486. if (childImpostor.physicsBody) {
  86487. _this.removePhysicsBody(childImpostor);
  86488. childImpostor.physicsBody = null;
  86489. }
  86490. childImpostor.parent = mainImpostor;
  86491. childImpostor.resetUpdateFlags();
  86492. 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));
  86493. //Add the mass of the children.
  86494. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86495. }
  86496. }
  86497. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86498. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86499. };
  86500. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86501. }
  86502. };
  86503. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86504. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86505. this.world.removeEventListener("preStep", impostor.beforeStep);
  86506. this.world.removeEventListener("postStep", impostor.afterStep);
  86507. this.world.remove(impostor.physicsBody);
  86508. };
  86509. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86510. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86511. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86512. if (!mainBody || !connectedBody) {
  86513. return;
  86514. }
  86515. var constraint;
  86516. var jointData = impostorJoint.joint.jointData;
  86517. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86518. var constraintData = {
  86519. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86520. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86521. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86522. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86523. maxForce: jointData.nativeParams.maxForce,
  86524. collideConnected: !!jointData.collision
  86525. };
  86526. switch (impostorJoint.joint.type) {
  86527. case BABYLON.PhysicsJoint.HingeJoint:
  86528. case BABYLON.PhysicsJoint.Hinge2Joint:
  86529. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86530. break;
  86531. case BABYLON.PhysicsJoint.DistanceJoint:
  86532. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86533. break;
  86534. case BABYLON.PhysicsJoint.SpringJoint:
  86535. var springData = jointData;
  86536. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86537. restLength: springData.length,
  86538. stiffness: springData.stiffness,
  86539. damping: springData.damping,
  86540. localAnchorA: constraintData.pivotA,
  86541. localAnchorB: constraintData.pivotB
  86542. });
  86543. break;
  86544. case BABYLON.PhysicsJoint.LockJoint:
  86545. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86546. break;
  86547. case BABYLON.PhysicsJoint.PointToPointJoint:
  86548. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86549. default:
  86550. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86551. break;
  86552. }
  86553. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86554. constraint.collideConnected = !!jointData.collision;
  86555. impostorJoint.joint.physicsJoint = constraint;
  86556. //don't add spring as constraint, as it is not one.
  86557. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86558. this.world.addConstraint(constraint);
  86559. }
  86560. else {
  86561. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86562. constraint.applyForce();
  86563. });
  86564. }
  86565. };
  86566. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86567. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86568. };
  86569. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86570. var index;
  86571. var mat;
  86572. for (index = 0; index < this._physicsMaterials.length; index++) {
  86573. mat = this._physicsMaterials[index];
  86574. if (mat.friction === friction && mat.restitution === restitution) {
  86575. return mat;
  86576. }
  86577. }
  86578. var currentMat = new this.BJSCANNON.Material(name);
  86579. currentMat.friction = friction;
  86580. currentMat.restitution = restitution;
  86581. this._physicsMaterials.push(currentMat);
  86582. return currentMat;
  86583. };
  86584. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86585. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86586. };
  86587. CannonJSPlugin.prototype._createShape = function (impostor) {
  86588. var object = impostor.object;
  86589. var returnValue;
  86590. var extendSize = impostor.getObjectExtendSize();
  86591. switch (impostor.type) {
  86592. case BABYLON.PhysicsImpostor.SphereImpostor:
  86593. var radiusX = extendSize.x;
  86594. var radiusY = extendSize.y;
  86595. var radiusZ = extendSize.z;
  86596. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86597. break;
  86598. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86599. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86600. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86601. break;
  86602. case BABYLON.PhysicsImpostor.BoxImpostor:
  86603. var box = extendSize.scale(0.5);
  86604. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86605. break;
  86606. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86607. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86608. returnValue = new this.BJSCANNON.Plane();
  86609. break;
  86610. case BABYLON.PhysicsImpostor.MeshImpostor:
  86611. // should transform the vertex data to world coordinates!!
  86612. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86613. var rawFaces = object.getIndices ? object.getIndices() : [];
  86614. if (!rawVerts)
  86615. return;
  86616. // get only scale! so the object could transform correctly.
  86617. var oldPosition = object.position.clone();
  86618. var oldRotation = object.rotation && object.rotation.clone();
  86619. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86620. object.position.copyFromFloats(0, 0, 0);
  86621. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86622. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86623. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86624. var transform = object.computeWorldMatrix(true);
  86625. // convert rawVerts to object space
  86626. var temp = new Array();
  86627. var index;
  86628. for (index = 0; index < rawVerts.length; index += 3) {
  86629. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86630. }
  86631. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86632. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86633. //now set back the transformation!
  86634. object.position.copyFrom(oldPosition);
  86635. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86636. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86637. break;
  86638. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86639. var oldPosition2 = object.position.clone();
  86640. var oldRotation2 = object.rotation && object.rotation.clone();
  86641. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86642. object.position.copyFromFloats(0, 0, 0);
  86643. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86644. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86645. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86646. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86647. returnValue = this._createHeightmap(object);
  86648. object.position.copyFrom(oldPosition2);
  86649. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86650. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86651. object.computeWorldMatrix(true);
  86652. break;
  86653. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86654. returnValue = new this.BJSCANNON.Particle();
  86655. break;
  86656. }
  86657. return returnValue;
  86658. };
  86659. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86660. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86661. var transform = object.computeWorldMatrix(true);
  86662. // convert rawVerts to object space
  86663. var temp = new Array();
  86664. var index;
  86665. for (index = 0; index < pos.length; index += 3) {
  86666. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86667. }
  86668. pos = temp;
  86669. var matrix = new Array();
  86670. //For now pointDepth will not be used and will be automatically calculated.
  86671. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86672. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86673. var boundingInfo = object.getBoundingInfo();
  86674. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86675. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86676. var elementSize = dim * 2 / arraySize;
  86677. for (var i = 0; i < pos.length; i = i + 3) {
  86678. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86679. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86680. var y = -pos[i + 2] + minY;
  86681. if (!matrix[x]) {
  86682. matrix[x] = [];
  86683. }
  86684. if (!matrix[x][z]) {
  86685. matrix[x][z] = y;
  86686. }
  86687. matrix[x][z] = Math.max(y, matrix[x][z]);
  86688. }
  86689. for (var x = 0; x <= arraySize; ++x) {
  86690. if (!matrix[x]) {
  86691. var loc = 1;
  86692. while (!matrix[(x + loc) % arraySize]) {
  86693. loc++;
  86694. }
  86695. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86696. //console.log("missing x", x);
  86697. }
  86698. for (var z = 0; z <= arraySize; ++z) {
  86699. if (!matrix[x][z]) {
  86700. var loc = 1;
  86701. var newValue;
  86702. while (newValue === undefined) {
  86703. newValue = matrix[x][(z + loc++) % arraySize];
  86704. }
  86705. matrix[x][z] = newValue;
  86706. }
  86707. }
  86708. }
  86709. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86710. elementSize: elementSize
  86711. });
  86712. //For future reference, needed for body transformation
  86713. shape.minY = minY;
  86714. return shape;
  86715. };
  86716. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86717. var object = impostor.object;
  86718. //make sure it is updated...
  86719. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86720. // The delta between the mesh position and the mesh bounding box center
  86721. var bInfo = object.getBoundingInfo();
  86722. if (!bInfo)
  86723. return;
  86724. var center = impostor.getObjectCenter();
  86725. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86726. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86727. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86728. this._tmpPosition.copyFrom(center);
  86729. var quaternion = object.rotationQuaternion;
  86730. if (!quaternion) {
  86731. return;
  86732. }
  86733. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86734. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86735. //-90 DEG in X, precalculated
  86736. quaternion = quaternion.multiply(this._minus90X);
  86737. //Invert! (Precalculated, 90 deg in X)
  86738. //No need to clone. this will never change.
  86739. impostor.setDeltaRotation(this._plus90X);
  86740. }
  86741. //If it is a heightfield, if should be centered.
  86742. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86743. var mesh = object;
  86744. var boundingInfo = mesh.getBoundingInfo();
  86745. //calculate the correct body position:
  86746. var rotationQuaternion = mesh.rotationQuaternion;
  86747. mesh.rotationQuaternion = this._tmpUnityRotation;
  86748. mesh.computeWorldMatrix(true);
  86749. //get original center with no rotation
  86750. var c = center.clone();
  86751. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86752. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86753. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86754. mesh.setPreTransformMatrix(p);
  86755. mesh.computeWorldMatrix(true);
  86756. //calculate the translation
  86757. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86758. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86759. //add it inverted to the delta
  86760. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86761. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86762. //rotation is back
  86763. mesh.rotationQuaternion = rotationQuaternion;
  86764. mesh.setPreTransformMatrix(oldPivot);
  86765. mesh.computeWorldMatrix(true);
  86766. }
  86767. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86768. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86769. //this._tmpPosition.copyFrom(object.position);
  86770. }
  86771. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86772. //Now update the impostor object
  86773. impostor.physicsBody.position.copy(this._tmpPosition);
  86774. impostor.physicsBody.quaternion.copy(quaternion);
  86775. };
  86776. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86777. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86778. if (impostor.object.rotationQuaternion) {
  86779. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86780. }
  86781. };
  86782. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86783. impostor.physicsBody.position.copy(newPosition);
  86784. impostor.physicsBody.quaternion.copy(newRotation);
  86785. };
  86786. CannonJSPlugin.prototype.isSupported = function () {
  86787. return this.BJSCANNON !== undefined;
  86788. };
  86789. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86790. impostor.physicsBody.velocity.copy(velocity);
  86791. };
  86792. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86793. impostor.physicsBody.angularVelocity.copy(velocity);
  86794. };
  86795. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86796. var v = impostor.physicsBody.velocity;
  86797. if (!v) {
  86798. return null;
  86799. }
  86800. return new BABYLON.Vector3(v.x, v.y, v.z);
  86801. };
  86802. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86803. var v = impostor.physicsBody.angularVelocity;
  86804. if (!v) {
  86805. return null;
  86806. }
  86807. return new BABYLON.Vector3(v.x, v.y, v.z);
  86808. };
  86809. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86810. impostor.physicsBody.mass = mass;
  86811. impostor.physicsBody.updateMassProperties();
  86812. };
  86813. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86814. return impostor.physicsBody.mass;
  86815. };
  86816. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86817. return impostor.physicsBody.material.friction;
  86818. };
  86819. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86820. impostor.physicsBody.material.friction = friction;
  86821. };
  86822. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86823. return impostor.physicsBody.material.restitution;
  86824. };
  86825. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86826. impostor.physicsBody.material.restitution = restitution;
  86827. };
  86828. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86829. impostor.physicsBody.sleep();
  86830. };
  86831. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86832. impostor.physicsBody.wakeUp();
  86833. };
  86834. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86835. joint.physicsJoint.distance = maxDistance;
  86836. };
  86837. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86838. // if (!motorIndex) {
  86839. // joint.physicsJoint.enableMotor();
  86840. // }
  86841. // }
  86842. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86843. // if (!motorIndex) {
  86844. // joint.physicsJoint.disableMotor();
  86845. // }
  86846. // }
  86847. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86848. if (!motorIndex) {
  86849. joint.physicsJoint.enableMotor();
  86850. joint.physicsJoint.setMotorSpeed(speed);
  86851. if (maxForce) {
  86852. this.setLimit(joint, maxForce);
  86853. }
  86854. }
  86855. };
  86856. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86857. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86858. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86859. };
  86860. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86861. var body = impostor.physicsBody;
  86862. mesh.position.x = body.position.x;
  86863. mesh.position.y = body.position.y;
  86864. mesh.position.z = body.position.z;
  86865. if (mesh.rotationQuaternion) {
  86866. mesh.rotationQuaternion.x = body.quaternion.x;
  86867. mesh.rotationQuaternion.y = body.quaternion.y;
  86868. mesh.rotationQuaternion.z = body.quaternion.z;
  86869. mesh.rotationQuaternion.w = body.quaternion.w;
  86870. }
  86871. };
  86872. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86873. var shape = impostor.physicsBody.shapes[0];
  86874. return shape.boundingSphereRadius;
  86875. };
  86876. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86877. var shape = impostor.physicsBody.shapes[0];
  86878. result.x = shape.halfExtents.x * 2;
  86879. result.y = shape.halfExtents.y * 2;
  86880. result.z = shape.halfExtents.z * 2;
  86881. };
  86882. CannonJSPlugin.prototype.dispose = function () {
  86883. };
  86884. CannonJSPlugin.prototype._extendNamespace = function () {
  86885. //this will force cannon to execute at least one step when using interpolation
  86886. var step_tmp1 = new this.BJSCANNON.Vec3();
  86887. var Engine = this.BJSCANNON;
  86888. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86889. maxSubSteps = maxSubSteps || 10;
  86890. timeSinceLastCalled = timeSinceLastCalled || 0;
  86891. if (timeSinceLastCalled === 0) {
  86892. this.internalStep(dt);
  86893. this.time += dt;
  86894. }
  86895. else {
  86896. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86897. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86898. var t0 = performance.now();
  86899. for (var i = 0; i !== internalSteps; i++) {
  86900. this.internalStep(dt);
  86901. if (performance.now() - t0 > dt * 1000) {
  86902. break;
  86903. }
  86904. }
  86905. this.time += timeSinceLastCalled;
  86906. var h = this.time % dt;
  86907. var h_div_dt = h / dt;
  86908. var interpvelo = step_tmp1;
  86909. var bodies = this.bodies;
  86910. for (var j = 0; j !== bodies.length; j++) {
  86911. var b = bodies[j];
  86912. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86913. b.position.vsub(b.previousPosition, interpvelo);
  86914. interpvelo.scale(h_div_dt, interpvelo);
  86915. b.position.vadd(interpvelo, b.interpolatedPosition);
  86916. }
  86917. else {
  86918. b.interpolatedPosition.copy(b.position);
  86919. b.interpolatedQuaternion.copy(b.quaternion);
  86920. }
  86921. }
  86922. }
  86923. };
  86924. };
  86925. return CannonJSPlugin;
  86926. }());
  86927. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86928. })(BABYLON || (BABYLON = {}));
  86929. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86930. var BABYLON;
  86931. (function (BABYLON) {
  86932. var OimoJSPlugin = /** @class */ (function () {
  86933. function OimoJSPlugin(iterations) {
  86934. this.name = "OimoJSPlugin";
  86935. this._tmpImpostorsArray = [];
  86936. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86937. this.BJSOIMO = OIMO;
  86938. this.world = new this.BJSOIMO.World({
  86939. iterations: iterations
  86940. });
  86941. this.world.clear();
  86942. }
  86943. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86944. this.world.gravity.copy(gravity);
  86945. };
  86946. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86947. this.world.timeStep = timeStep;
  86948. };
  86949. OimoJSPlugin.prototype.getTimeStep = function () {
  86950. return this.world.timeStep;
  86951. };
  86952. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86953. var _this = this;
  86954. impostors.forEach(function (impostor) {
  86955. impostor.beforeStep();
  86956. });
  86957. this.world.step();
  86958. impostors.forEach(function (impostor) {
  86959. impostor.afterStep();
  86960. //update the ordered impostors array
  86961. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86962. });
  86963. //check for collisions
  86964. var contact = this.world.contacts;
  86965. while (contact !== null) {
  86966. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86967. contact = contact.next;
  86968. continue;
  86969. }
  86970. //is this body colliding with any other? get the impostor
  86971. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86972. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86973. if (!mainImpostor || !collidingImpostor) {
  86974. contact = contact.next;
  86975. continue;
  86976. }
  86977. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86978. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86979. contact = contact.next;
  86980. }
  86981. };
  86982. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86983. var mass = impostor.physicsBody.mass;
  86984. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86985. };
  86986. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86987. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86988. this.applyImpulse(impostor, force, contactPoint);
  86989. };
  86990. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86991. var _this = this;
  86992. //parent-child relationship. Does this impostor has a parent impostor?
  86993. if (impostor.parent) {
  86994. if (impostor.physicsBody) {
  86995. this.removePhysicsBody(impostor);
  86996. //TODO is that needed?
  86997. impostor.forceUpdate();
  86998. }
  86999. return;
  87000. }
  87001. if (impostor.isBodyInitRequired()) {
  87002. var bodyConfig = {
  87003. name: impostor.uniqueId,
  87004. //Oimo must have mass, also for static objects.
  87005. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  87006. size: [],
  87007. type: [],
  87008. pos: [],
  87009. posShape: [],
  87010. rot: [],
  87011. rotShape: [],
  87012. move: impostor.getParam("mass") !== 0,
  87013. density: impostor.getParam("mass"),
  87014. friction: impostor.getParam("friction"),
  87015. restitution: impostor.getParam("restitution"),
  87016. //Supporting older versions of Oimo
  87017. world: this.world
  87018. };
  87019. var impostors = [impostor];
  87020. var addToArray = function (parent) {
  87021. if (!parent.getChildMeshes)
  87022. return;
  87023. parent.getChildMeshes().forEach(function (m) {
  87024. if (m.physicsImpostor) {
  87025. impostors.push(m.physicsImpostor);
  87026. //m.physicsImpostor._init();
  87027. }
  87028. });
  87029. };
  87030. addToArray(impostor.object);
  87031. var checkWithEpsilon_1 = function (value) {
  87032. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  87033. };
  87034. var globalQuaternion_1 = new BABYLON.Quaternion();
  87035. impostors.forEach(function (i) {
  87036. if (!i.object.rotationQuaternion) {
  87037. return;
  87038. }
  87039. //get the correct bounding box
  87040. var oldQuaternion = i.object.rotationQuaternion;
  87041. globalQuaternion_1 = oldQuaternion.clone();
  87042. var rot = oldQuaternion.toEulerAngles();
  87043. var extendSize = i.getObjectExtendSize();
  87044. var radToDeg = 57.295779513082320876;
  87045. if (i === impostor) {
  87046. var center = impostor.getObjectCenter();
  87047. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  87048. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  87049. //Can also use Array.prototype.push.apply
  87050. bodyConfig.pos.push(center.x);
  87051. bodyConfig.pos.push(center.y);
  87052. bodyConfig.pos.push(center.z);
  87053. bodyConfig.posShape.push(0, 0, 0);
  87054. //tmp solution
  87055. bodyConfig.rot.push(0);
  87056. bodyConfig.rot.push(0);
  87057. bodyConfig.rot.push(0);
  87058. bodyConfig.rotShape.push(0, 0, 0);
  87059. }
  87060. else {
  87061. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  87062. bodyConfig.posShape.push(localPosition.x);
  87063. bodyConfig.posShape.push(localPosition.y);
  87064. bodyConfig.posShape.push(localPosition.z);
  87065. bodyConfig.pos.push(0, 0, 0);
  87066. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  87067. bodyConfig.rot.push(0);
  87068. bodyConfig.rot.push(0);
  87069. bodyConfig.rot.push(0);
  87070. bodyConfig.rotShape.push(rot.x * radToDeg);
  87071. bodyConfig.rotShape.push(rot.y * radToDeg);
  87072. bodyConfig.rotShape.push(rot.z * radToDeg);
  87073. }
  87074. // register mesh
  87075. switch (i.type) {
  87076. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87077. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  87078. case BABYLON.PhysicsImpostor.SphereImpostor:
  87079. var radiusX = extendSize.x;
  87080. var radiusY = extendSize.y;
  87081. var radiusZ = extendSize.z;
  87082. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  87083. bodyConfig.type.push('sphere');
  87084. //due to the way oimo works with compounds, add 3 times
  87085. bodyConfig.size.push(size);
  87086. bodyConfig.size.push(size);
  87087. bodyConfig.size.push(size);
  87088. break;
  87089. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87090. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  87091. var sizeY = checkWithEpsilon_1(extendSize.y);
  87092. bodyConfig.type.push('cylinder');
  87093. bodyConfig.size.push(sizeX);
  87094. bodyConfig.size.push(sizeY);
  87095. //due to the way oimo works with compounds, add one more value.
  87096. bodyConfig.size.push(sizeY);
  87097. break;
  87098. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87099. case BABYLON.PhysicsImpostor.BoxImpostor:
  87100. default:
  87101. var sizeX = checkWithEpsilon_1(extendSize.x);
  87102. var sizeY = checkWithEpsilon_1(extendSize.y);
  87103. var sizeZ = checkWithEpsilon_1(extendSize.z);
  87104. bodyConfig.type.push('box');
  87105. //if (i === impostor) {
  87106. bodyConfig.size.push(sizeX);
  87107. bodyConfig.size.push(sizeY);
  87108. bodyConfig.size.push(sizeZ);
  87109. //} else {
  87110. // bodyConfig.size.push(0,0,0);
  87111. //}
  87112. break;
  87113. }
  87114. //actually not needed, but hey...
  87115. i.object.rotationQuaternion = oldQuaternion;
  87116. });
  87117. impostor.physicsBody = this.world.add(bodyConfig);
  87118. // set the quaternion, ignoring the previously defined (euler) rotation
  87119. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  87120. // update with delta 0, so the body will reveive the new rotation.
  87121. impostor.physicsBody.updatePosition(0);
  87122. }
  87123. else {
  87124. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  87125. }
  87126. impostor.setDeltaPosition(this._tmpPositionVector);
  87127. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  87128. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  87129. };
  87130. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87131. //impostor.physicsBody.dispose();
  87132. //Same as : (older oimo versions)
  87133. this.world.removeRigidBody(impostor.physicsBody);
  87134. };
  87135. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87136. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87137. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87138. if (!mainBody || !connectedBody) {
  87139. return;
  87140. }
  87141. var jointData = impostorJoint.joint.jointData;
  87142. var options = jointData.nativeParams || {};
  87143. var type;
  87144. var nativeJointData = {
  87145. body1: mainBody,
  87146. body2: connectedBody,
  87147. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  87148. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  87149. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  87150. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  87151. min: options.min,
  87152. max: options.max,
  87153. collision: options.collision || jointData.collision,
  87154. spring: options.spring,
  87155. //supporting older version of Oimo
  87156. world: this.world
  87157. };
  87158. switch (impostorJoint.joint.type) {
  87159. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87160. type = "jointBall";
  87161. break;
  87162. case BABYLON.PhysicsJoint.SpringJoint:
  87163. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  87164. var springData = jointData;
  87165. nativeJointData.min = springData.length || nativeJointData.min;
  87166. //Max should also be set, just make sure it is at least min
  87167. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  87168. case BABYLON.PhysicsJoint.DistanceJoint:
  87169. type = "jointDistance";
  87170. nativeJointData.max = jointData.maxDistance;
  87171. break;
  87172. case BABYLON.PhysicsJoint.PrismaticJoint:
  87173. type = "jointPrisme";
  87174. break;
  87175. case BABYLON.PhysicsJoint.SliderJoint:
  87176. type = "jointSlide";
  87177. break;
  87178. case BABYLON.PhysicsJoint.WheelJoint:
  87179. type = "jointWheel";
  87180. break;
  87181. case BABYLON.PhysicsJoint.HingeJoint:
  87182. default:
  87183. type = "jointHinge";
  87184. break;
  87185. }
  87186. nativeJointData.type = type;
  87187. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  87188. };
  87189. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87190. //Bug in Oimo prevents us from disposing a joint in the playground
  87191. //joint.joint.physicsJoint.dispose();
  87192. //So we will bruteforce it!
  87193. try {
  87194. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  87195. }
  87196. catch (e) {
  87197. BABYLON.Tools.Warn(e);
  87198. }
  87199. };
  87200. OimoJSPlugin.prototype.isSupported = function () {
  87201. return this.BJSOIMO !== undefined;
  87202. };
  87203. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87204. if (!impostor.physicsBody.sleeping) {
  87205. //TODO check that
  87206. /*if (impostor.physicsBody.shapes.next) {
  87207. var parentShape = this._getLastShape(impostor.physicsBody);
  87208. impostor.object.position.copyFrom(parentShape.position);
  87209. console.log(parentShape.position);
  87210. } else {*/
  87211. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  87212. //}
  87213. if (impostor.object.rotationQuaternion) {
  87214. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  87215. }
  87216. }
  87217. };
  87218. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87219. var body = impostor.physicsBody;
  87220. body.position.copy(newPosition);
  87221. body.orientation.copy(newRotation);
  87222. body.syncShapes();
  87223. body.awake();
  87224. };
  87225. /*private _getLastShape(body: any): any {
  87226. var lastShape = body.shapes;
  87227. while (lastShape.next) {
  87228. lastShape = lastShape.next;
  87229. }
  87230. return lastShape;
  87231. }*/
  87232. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87233. impostor.physicsBody.linearVelocity.copy(velocity);
  87234. };
  87235. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87236. impostor.physicsBody.angularVelocity.copy(velocity);
  87237. };
  87238. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87239. var v = impostor.physicsBody.linearVelocity;
  87240. if (!v) {
  87241. return null;
  87242. }
  87243. return new BABYLON.Vector3(v.x, v.y, v.z);
  87244. };
  87245. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87246. var v = impostor.physicsBody.angularVelocity;
  87247. if (!v) {
  87248. return null;
  87249. }
  87250. return new BABYLON.Vector3(v.x, v.y, v.z);
  87251. };
  87252. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87253. var staticBody = mass === 0;
  87254. //this will actually set the body's density and not its mass.
  87255. //But this is how oimo treats the mass variable.
  87256. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  87257. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  87258. };
  87259. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  87260. return impostor.physicsBody.shapes.density;
  87261. };
  87262. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  87263. return impostor.physicsBody.shapes.friction;
  87264. };
  87265. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87266. impostor.physicsBody.shapes.friction = friction;
  87267. };
  87268. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87269. return impostor.physicsBody.shapes.restitution;
  87270. };
  87271. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87272. impostor.physicsBody.shapes.restitution = restitution;
  87273. };
  87274. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  87275. impostor.physicsBody.sleep();
  87276. };
  87277. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  87278. impostor.physicsBody.awake();
  87279. };
  87280. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87281. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  87282. if (minDistance !== void 0) {
  87283. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  87284. }
  87285. };
  87286. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87287. //TODO separate rotational and transational motors.
  87288. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87289. if (motor) {
  87290. motor.setMotor(speed, maxForce);
  87291. }
  87292. };
  87293. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  87294. //TODO separate rotational and transational motors.
  87295. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87296. if (motor) {
  87297. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  87298. }
  87299. };
  87300. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87301. var body = impostor.physicsBody;
  87302. mesh.position.x = body.position.x;
  87303. mesh.position.y = body.position.y;
  87304. mesh.position.z = body.position.z;
  87305. if (mesh.rotationQuaternion) {
  87306. mesh.rotationQuaternion.x = body.orientation.x;
  87307. mesh.rotationQuaternion.y = body.orientation.y;
  87308. mesh.rotationQuaternion.z = body.orientation.z;
  87309. mesh.rotationQuaternion.w = body.orientation.s;
  87310. }
  87311. };
  87312. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87313. return impostor.physicsBody.shapes.radius;
  87314. };
  87315. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87316. var shape = impostor.physicsBody.shapes;
  87317. result.x = shape.halfWidth * 2;
  87318. result.y = shape.halfHeight * 2;
  87319. result.z = shape.halfDepth * 2;
  87320. };
  87321. OimoJSPlugin.prototype.dispose = function () {
  87322. this.world.clear();
  87323. };
  87324. return OimoJSPlugin;
  87325. }());
  87326. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87327. })(BABYLON || (BABYLON = {}));
  87328. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87329. var BABYLON;
  87330. (function (BABYLON) {
  87331. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87332. // All values and structures referenced from:
  87333. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87334. var DDS_MAGIC = 0x20534444;
  87335. var
  87336. //DDSD_CAPS = 0x1,
  87337. //DDSD_HEIGHT = 0x2,
  87338. //DDSD_WIDTH = 0x4,
  87339. //DDSD_PITCH = 0x8,
  87340. //DDSD_PIXELFORMAT = 0x1000,
  87341. DDSD_MIPMAPCOUNT = 0x20000;
  87342. //DDSD_LINEARSIZE = 0x80000,
  87343. //DDSD_DEPTH = 0x800000;
  87344. // var DDSCAPS_COMPLEX = 0x8,
  87345. // DDSCAPS_MIPMAP = 0x400000,
  87346. // DDSCAPS_TEXTURE = 0x1000;
  87347. var DDSCAPS2_CUBEMAP = 0x200;
  87348. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87349. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87350. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87351. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87352. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87353. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87354. // DDSCAPS2_VOLUME = 0x200000;
  87355. var
  87356. //DDPF_ALPHAPIXELS = 0x1,
  87357. //DDPF_ALPHA = 0x2,
  87358. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87359. //DDPF_YUV = 0x200,
  87360. DDPF_LUMINANCE = 0x20000;
  87361. function FourCCToInt32(value) {
  87362. return value.charCodeAt(0) +
  87363. (value.charCodeAt(1) << 8) +
  87364. (value.charCodeAt(2) << 16) +
  87365. (value.charCodeAt(3) << 24);
  87366. }
  87367. function Int32ToFourCC(value) {
  87368. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87369. }
  87370. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87371. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87372. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87373. var FOURCC_DX10 = FourCCToInt32("DX10");
  87374. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87375. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87376. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87377. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87378. var headerLengthInt = 31; // The header length in 32 bit ints
  87379. // Offsets into the header array
  87380. var off_magic = 0;
  87381. var off_size = 1;
  87382. var off_flags = 2;
  87383. var off_height = 3;
  87384. var off_width = 4;
  87385. var off_mipmapCount = 7;
  87386. var off_pfFlags = 20;
  87387. var off_pfFourCC = 21;
  87388. var off_RGBbpp = 22;
  87389. var off_RMask = 23;
  87390. var off_GMask = 24;
  87391. var off_BMask = 25;
  87392. var off_AMask = 26;
  87393. // var off_caps1 = 27;
  87394. var off_caps2 = 28;
  87395. // var off_caps3 = 29;
  87396. // var off_caps4 = 30;
  87397. var off_dxgiFormat = 32;
  87398. ;
  87399. var DDSTools = /** @class */ (function () {
  87400. function DDSTools() {
  87401. }
  87402. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87403. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87404. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87405. var mipmapCount = 1;
  87406. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87407. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87408. }
  87409. var fourCC = header[off_pfFourCC];
  87410. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87411. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87412. switch (fourCC) {
  87413. case FOURCC_D3DFMT_R16G16B16A16F:
  87414. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87415. break;
  87416. case FOURCC_D3DFMT_R32G32B32A32F:
  87417. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87418. break;
  87419. case FOURCC_DX10:
  87420. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87421. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87422. break;
  87423. }
  87424. }
  87425. return {
  87426. width: header[off_width],
  87427. height: header[off_height],
  87428. mipmapCount: mipmapCount,
  87429. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87430. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87431. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87432. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87433. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87434. dxgiFormat: dxgiFormat,
  87435. textureType: textureType
  87436. };
  87437. };
  87438. DDSTools._ToHalfFloat = function (value) {
  87439. if (!DDSTools._FloatView) {
  87440. DDSTools._FloatView = new Float32Array(1);
  87441. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87442. }
  87443. DDSTools._FloatView[0] = value;
  87444. var x = DDSTools._Int32View[0];
  87445. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87446. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87447. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87448. /* If zero, or denormal, or exponent underflows too much for a denormal
  87449. * half, return signed zero. */
  87450. if (e < 103) {
  87451. return bits;
  87452. }
  87453. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87454. if (e > 142) {
  87455. bits |= 0x7c00;
  87456. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87457. * not Inf, so make sure we set one mantissa bit too. */
  87458. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87459. return bits;
  87460. }
  87461. /* If exponent underflows but not too much, return a denormal */
  87462. if (e < 113) {
  87463. m |= 0x0800;
  87464. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87465. * to 1, which is OK. */
  87466. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87467. return bits;
  87468. }
  87469. bits |= ((e - 112) << 10) | (m >> 1);
  87470. bits += m & 1;
  87471. return bits;
  87472. };
  87473. DDSTools._FromHalfFloat = function (value) {
  87474. var s = (value & 0x8000) >> 15;
  87475. var e = (value & 0x7C00) >> 10;
  87476. var f = value & 0x03FF;
  87477. if (e === 0) {
  87478. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87479. }
  87480. else if (e == 0x1F) {
  87481. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87482. }
  87483. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87484. };
  87485. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87486. var destArray = new Float32Array(dataLength);
  87487. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87488. var index = 0;
  87489. for (var y = 0; y < height; y++) {
  87490. for (var x = 0; x < width; x++) {
  87491. var srcPos = (x + y * width) * 4;
  87492. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87493. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87494. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87495. if (DDSTools.StoreLODInAlphaChannel) {
  87496. destArray[index + 3] = lod;
  87497. }
  87498. else {
  87499. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87500. }
  87501. index += 4;
  87502. }
  87503. }
  87504. return destArray;
  87505. };
  87506. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87507. if (DDSTools.StoreLODInAlphaChannel) {
  87508. var destArray = new Uint16Array(dataLength);
  87509. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87510. var index = 0;
  87511. for (var y = 0; y < height; y++) {
  87512. for (var x = 0; x < width; x++) {
  87513. var srcPos = (x + y * width) * 4;
  87514. destArray[index] = srcData[srcPos];
  87515. destArray[index + 1] = srcData[srcPos + 1];
  87516. destArray[index + 2] = srcData[srcPos + 2];
  87517. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87518. index += 4;
  87519. }
  87520. }
  87521. return destArray;
  87522. }
  87523. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87524. };
  87525. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87526. if (DDSTools.StoreLODInAlphaChannel) {
  87527. var destArray = new Float32Array(dataLength);
  87528. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87529. var index = 0;
  87530. for (var y = 0; y < height; y++) {
  87531. for (var x = 0; x < width; x++) {
  87532. var srcPos = (x + y * width) * 4;
  87533. destArray[index] = srcData[srcPos];
  87534. destArray[index + 1] = srcData[srcPos + 1];
  87535. destArray[index + 2] = srcData[srcPos + 2];
  87536. destArray[index + 3] = lod;
  87537. index += 4;
  87538. }
  87539. }
  87540. return destArray;
  87541. }
  87542. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87543. };
  87544. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87545. var destArray = new Uint8Array(dataLength);
  87546. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87547. var index = 0;
  87548. for (var y = 0; y < height; y++) {
  87549. for (var x = 0; x < width; x++) {
  87550. var srcPos = (x + y * width) * 4;
  87551. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87552. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87553. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87554. if (DDSTools.StoreLODInAlphaChannel) {
  87555. destArray[index + 3] = lod;
  87556. }
  87557. else {
  87558. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87559. }
  87560. index += 4;
  87561. }
  87562. }
  87563. return destArray;
  87564. };
  87565. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87566. var destArray = new Uint8Array(dataLength);
  87567. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87568. var index = 0;
  87569. for (var y = 0; y < height; y++) {
  87570. for (var x = 0; x < width; x++) {
  87571. var srcPos = (x + y * width) * 4;
  87572. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87573. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87574. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87575. if (DDSTools.StoreLODInAlphaChannel) {
  87576. destArray[index + 3] = lod;
  87577. }
  87578. else {
  87579. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87580. }
  87581. index += 4;
  87582. }
  87583. }
  87584. return destArray;
  87585. };
  87586. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87587. var byteArray = new Uint8Array(dataLength);
  87588. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87589. var index = 0;
  87590. for (var y = 0; y < height; y++) {
  87591. for (var x = 0; x < width; x++) {
  87592. var srcPos = (x + y * width) * 4;
  87593. byteArray[index] = srcData[srcPos + rOffset];
  87594. byteArray[index + 1] = srcData[srcPos + gOffset];
  87595. byteArray[index + 2] = srcData[srcPos + bOffset];
  87596. byteArray[index + 3] = srcData[srcPos + aOffset];
  87597. index += 4;
  87598. }
  87599. }
  87600. return byteArray;
  87601. };
  87602. DDSTools._ExtractLongWordOrder = function (value) {
  87603. if (value === 0 || value === 255 || value === -16777216) {
  87604. return 0;
  87605. }
  87606. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87607. };
  87608. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87609. var byteArray = new Uint8Array(dataLength);
  87610. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87611. var index = 0;
  87612. for (var y = 0; y < height; y++) {
  87613. for (var x = 0; x < width; x++) {
  87614. var srcPos = (x + y * width) * 3;
  87615. byteArray[index] = srcData[srcPos + rOffset];
  87616. byteArray[index + 1] = srcData[srcPos + gOffset];
  87617. byteArray[index + 2] = srcData[srcPos + bOffset];
  87618. index += 3;
  87619. }
  87620. }
  87621. return byteArray;
  87622. };
  87623. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87624. var byteArray = new Uint8Array(dataLength);
  87625. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87626. var index = 0;
  87627. for (var y = 0; y < height; y++) {
  87628. for (var x = 0; x < width; x++) {
  87629. var srcPos = (x + y * width);
  87630. byteArray[index] = srcData[srcPos];
  87631. index++;
  87632. }
  87633. }
  87634. return byteArray;
  87635. };
  87636. /**
  87637. * Uploads DDS Levels to a Babylon Texture
  87638. * @hidden
  87639. */
  87640. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87641. if (lodIndex === void 0) { lodIndex = -1; }
  87642. var sphericalPolynomialFaces = null;
  87643. if (info.sphericalPolynomial) {
  87644. sphericalPolynomialFaces = new Array();
  87645. }
  87646. var ext = engine.getCaps().s3tc;
  87647. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87648. var fourCC, width, height, dataLength = 0, dataOffset;
  87649. var byteArray, mipmapCount, mip;
  87650. var internalCompressedFormat = 0;
  87651. var blockBytes = 1;
  87652. if (header[off_magic] !== DDS_MAGIC) {
  87653. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87654. return;
  87655. }
  87656. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87657. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87658. return;
  87659. }
  87660. if (info.isCompressed && !ext) {
  87661. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87662. return;
  87663. }
  87664. var bpp = header[off_RGBbpp];
  87665. dataOffset = header[off_size] + 4;
  87666. var computeFormats = false;
  87667. if (info.isFourCC) {
  87668. fourCC = header[off_pfFourCC];
  87669. switch (fourCC) {
  87670. case FOURCC_DXT1:
  87671. blockBytes = 8;
  87672. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87673. break;
  87674. case FOURCC_DXT3:
  87675. blockBytes = 16;
  87676. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87677. break;
  87678. case FOURCC_DXT5:
  87679. blockBytes = 16;
  87680. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87681. break;
  87682. case FOURCC_D3DFMT_R16G16B16A16F:
  87683. computeFormats = true;
  87684. break;
  87685. case FOURCC_D3DFMT_R32G32B32A32F:
  87686. computeFormats = true;
  87687. break;
  87688. case FOURCC_DX10:
  87689. // There is an additionnal header so dataOffset need to be changed
  87690. dataOffset += 5 * 4; // 5 uints
  87691. var supported = false;
  87692. switch (info.dxgiFormat) {
  87693. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87694. computeFormats = true;
  87695. supported = true;
  87696. break;
  87697. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87698. info.isRGB = true;
  87699. info.isFourCC = false;
  87700. bpp = 32;
  87701. supported = true;
  87702. break;
  87703. }
  87704. if (supported) {
  87705. break;
  87706. }
  87707. default:
  87708. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87709. return;
  87710. }
  87711. }
  87712. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87713. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87714. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87715. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87716. if (computeFormats) {
  87717. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87718. }
  87719. mipmapCount = 1;
  87720. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87721. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87722. }
  87723. for (var face = 0; face < faces; face++) {
  87724. width = header[off_width];
  87725. height = header[off_height];
  87726. for (mip = 0; mip < mipmapCount; ++mip) {
  87727. if (lodIndex === -1 || lodIndex === mip) {
  87728. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87729. var i = (lodIndex === -1) ? mip : 0;
  87730. if (!info.isCompressed && info.isFourCC) {
  87731. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87732. dataLength = width * height * 4;
  87733. var floatArray = null;
  87734. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87735. if (bpp === 128) {
  87736. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87737. if (sphericalPolynomialFaces && i == 0) {
  87738. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87739. }
  87740. }
  87741. else if (bpp === 64) {
  87742. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87743. if (sphericalPolynomialFaces && i == 0) {
  87744. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87745. }
  87746. }
  87747. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87748. }
  87749. else {
  87750. if (bpp === 128) {
  87751. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87752. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87753. if (sphericalPolynomialFaces && i == 0) {
  87754. sphericalPolynomialFaces.push(floatArray);
  87755. }
  87756. }
  87757. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87758. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87759. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87760. if (sphericalPolynomialFaces && i == 0) {
  87761. sphericalPolynomialFaces.push(floatArray);
  87762. }
  87763. }
  87764. else { // 64
  87765. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87766. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87767. if (sphericalPolynomialFaces && i == 0) {
  87768. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87769. }
  87770. }
  87771. }
  87772. if (floatArray) {
  87773. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  87774. }
  87775. }
  87776. else if (info.isRGB) {
  87777. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87778. if (bpp === 24) {
  87779. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  87780. dataLength = width * height * 3;
  87781. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87782. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87783. }
  87784. else { // 32
  87785. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87786. dataLength = width * height * 4;
  87787. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87788. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87789. }
  87790. }
  87791. else if (info.isLuminance) {
  87792. var unpackAlignment = engine._getUnpackAlignement();
  87793. var unpaddedRowSize = width;
  87794. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87795. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87796. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87797. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  87798. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87799. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87800. }
  87801. else {
  87802. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87803. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87804. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87805. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  87806. }
  87807. }
  87808. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87809. width *= 0.5;
  87810. height *= 0.5;
  87811. width = Math.max(1.0, width);
  87812. height = Math.max(1.0, height);
  87813. }
  87814. if (currentFace !== undefined) {
  87815. // Loading a single face
  87816. break;
  87817. }
  87818. }
  87819. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87820. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87821. size: header[off_width],
  87822. right: sphericalPolynomialFaces[0],
  87823. left: sphericalPolynomialFaces[1],
  87824. up: sphericalPolynomialFaces[2],
  87825. down: sphericalPolynomialFaces[3],
  87826. front: sphericalPolynomialFaces[4],
  87827. back: sphericalPolynomialFaces[5],
  87828. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87829. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87830. gammaSpace: false,
  87831. });
  87832. }
  87833. else {
  87834. info.sphericalPolynomial = undefined;
  87835. }
  87836. };
  87837. DDSTools.StoreLODInAlphaChannel = false;
  87838. return DDSTools;
  87839. }());
  87840. BABYLON.DDSTools = DDSTools;
  87841. })(BABYLON || (BABYLON = {}));
  87842. //# sourceMappingURL=babylon.dds.js.map
  87843. var BABYLON;
  87844. (function (BABYLON) {
  87845. /**
  87846. * Implementation of the DDS Texture Loader.
  87847. */
  87848. var DDSTextureLoader = /** @class */ (function () {
  87849. function DDSTextureLoader() {
  87850. /**
  87851. * Defines wether the loader supports cascade loading the different faces.
  87852. */
  87853. this.supportCascades = true;
  87854. }
  87855. /**
  87856. * This returns if the loader support the current file information.
  87857. * @param extension defines the file extension of the file being loaded
  87858. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87859. * @param fallback defines the fallback internal texture if any
  87860. * @param isBase64 defines whether the texture is encoded as a base64
  87861. * @param isBuffer defines whether the texture data are stored as a buffer
  87862. * @returns true if the loader can load the specified file
  87863. */
  87864. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  87865. return extension.indexOf(".dds") === 0;
  87866. };
  87867. /**
  87868. * Transform the url before loading if required.
  87869. * @param rootUrl the url of the texture
  87870. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87871. * @returns the transformed texture
  87872. */
  87873. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  87874. return rootUrl;
  87875. };
  87876. /**
  87877. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  87878. * @param rootUrl the url of the texture
  87879. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87880. * @returns the fallback texture
  87881. */
  87882. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  87883. return null;
  87884. };
  87885. /**
  87886. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  87887. * @param data contains the texture data
  87888. * @param texture defines the BabylonJS internal texture
  87889. * @param createPolynomials will be true if polynomials have been requested
  87890. * @param onLoad defines the callback to trigger once the texture is ready
  87891. * @param onError defines the callback to trigger in case of error
  87892. */
  87893. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  87894. var engine = texture.getEngine();
  87895. var info;
  87896. var loadMipmap = false;
  87897. if (Array.isArray(imgs)) {
  87898. for (var index = 0; index < imgs.length; index++) {
  87899. var data_1 = imgs[index];
  87900. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  87901. texture.width = info.width;
  87902. texture.height = info.height;
  87903. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  87904. engine._unpackFlipY(info.isCompressed);
  87905. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  87906. if (!info.isFourCC && info.mipmapCount === 1) {
  87907. engine.generateMipMapsForCubemap(texture);
  87908. }
  87909. }
  87910. }
  87911. else {
  87912. var data = imgs;
  87913. info = BABYLON.DDSTools.GetDDSInfo(data);
  87914. texture.width = info.width;
  87915. texture.height = info.height;
  87916. if (createPolynomials) {
  87917. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  87918. }
  87919. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  87920. engine._unpackFlipY(info.isCompressed);
  87921. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  87922. if (!info.isFourCC && info.mipmapCount === 1) {
  87923. engine.generateMipMapsForCubemap(texture);
  87924. }
  87925. }
  87926. engine._setCubeMapTextureParams(loadMipmap);
  87927. texture.isReady = true;
  87928. if (onLoad) {
  87929. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  87930. }
  87931. };
  87932. /**
  87933. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  87934. * @param data contains the texture data
  87935. * @param texture defines the BabylonJS internal texture
  87936. * @param callback defines the method to call once ready to upload
  87937. */
  87938. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  87939. var info = BABYLON.DDSTools.GetDDSInfo(data);
  87940. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  87941. callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {
  87942. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  87943. });
  87944. };
  87945. return DDSTextureLoader;
  87946. }());
  87947. // Register the loader.
  87948. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  87949. })(BABYLON || (BABYLON = {}));
  87950. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  87951. var BABYLON;
  87952. (function (BABYLON) {
  87953. /*
  87954. * Based on jsTGALoader - Javascript loader for TGA file
  87955. * By Vincent Thibault
  87956. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  87957. */
  87958. var TGATools = /** @class */ (function () {
  87959. function TGATools() {
  87960. }
  87961. TGATools.GetTGAHeader = function (data) {
  87962. var offset = 0;
  87963. var header = {
  87964. id_length: data[offset++],
  87965. colormap_type: data[offset++],
  87966. image_type: data[offset++],
  87967. colormap_index: data[offset++] | data[offset++] << 8,
  87968. colormap_length: data[offset++] | data[offset++] << 8,
  87969. colormap_size: data[offset++],
  87970. origin: [
  87971. data[offset++] | data[offset++] << 8,
  87972. data[offset++] | data[offset++] << 8
  87973. ],
  87974. width: data[offset++] | data[offset++] << 8,
  87975. height: data[offset++] | data[offset++] << 8,
  87976. pixel_size: data[offset++],
  87977. flags: data[offset++]
  87978. };
  87979. return header;
  87980. };
  87981. /**
  87982. * Uploads TGA content to a Babylon Texture
  87983. * @hidden
  87984. */
  87985. TGATools.UploadContent = function (texture, data) {
  87986. // Not enough data to contain header ?
  87987. if (data.length < 19) {
  87988. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87989. return;
  87990. }
  87991. // Read Header
  87992. var offset = 18;
  87993. var header = TGATools.GetTGAHeader(data);
  87994. // Assume it's a valid Targa file.
  87995. if (header.id_length + offset > data.length) {
  87996. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87997. return;
  87998. }
  87999. // Skip not needed data
  88000. offset += header.id_length;
  88001. var use_rle = false;
  88002. var use_pal = false;
  88003. var use_grey = false;
  88004. // Get some informations.
  88005. switch (header.image_type) {
  88006. case TGATools._TYPE_RLE_INDEXED:
  88007. use_rle = true;
  88008. case TGATools._TYPE_INDEXED:
  88009. use_pal = true;
  88010. break;
  88011. case TGATools._TYPE_RLE_RGB:
  88012. use_rle = true;
  88013. case TGATools._TYPE_RGB:
  88014. // use_rgb = true;
  88015. break;
  88016. case TGATools._TYPE_RLE_GREY:
  88017. use_rle = true;
  88018. case TGATools._TYPE_GREY:
  88019. use_grey = true;
  88020. break;
  88021. }
  88022. var pixel_data;
  88023. // var numAlphaBits = header.flags & 0xf;
  88024. var pixel_size = header.pixel_size >> 3;
  88025. var pixel_total = header.width * header.height * pixel_size;
  88026. // Read palettes
  88027. var palettes;
  88028. if (use_pal) {
  88029. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  88030. }
  88031. // Read LRE
  88032. if (use_rle) {
  88033. pixel_data = new Uint8Array(pixel_total);
  88034. var c, count, i;
  88035. var localOffset = 0;
  88036. var pixels = new Uint8Array(pixel_size);
  88037. while (offset < pixel_total && localOffset < pixel_total) {
  88038. c = data[offset++];
  88039. count = (c & 0x7f) + 1;
  88040. // RLE pixels
  88041. if (c & 0x80) {
  88042. // Bind pixel tmp array
  88043. for (i = 0; i < pixel_size; ++i) {
  88044. pixels[i] = data[offset++];
  88045. }
  88046. // Copy pixel array
  88047. for (i = 0; i < count; ++i) {
  88048. pixel_data.set(pixels, localOffset + i * pixel_size);
  88049. }
  88050. localOffset += pixel_size * count;
  88051. }
  88052. // Raw pixels
  88053. else {
  88054. count *= pixel_size;
  88055. for (i = 0; i < count; ++i) {
  88056. pixel_data[localOffset + i] = data[offset++];
  88057. }
  88058. localOffset += count;
  88059. }
  88060. }
  88061. }
  88062. // RAW Pixels
  88063. else {
  88064. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  88065. }
  88066. // Load to texture
  88067. var x_start, y_start, x_step, y_step, y_end, x_end;
  88068. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  88069. default:
  88070. case TGATools._ORIGIN_UL:
  88071. x_start = 0;
  88072. x_step = 1;
  88073. x_end = header.width;
  88074. y_start = 0;
  88075. y_step = 1;
  88076. y_end = header.height;
  88077. break;
  88078. case TGATools._ORIGIN_BL:
  88079. x_start = 0;
  88080. x_step = 1;
  88081. x_end = header.width;
  88082. y_start = header.height - 1;
  88083. y_step = -1;
  88084. y_end = -1;
  88085. break;
  88086. case TGATools._ORIGIN_UR:
  88087. x_start = header.width - 1;
  88088. x_step = -1;
  88089. x_end = -1;
  88090. y_start = 0;
  88091. y_step = 1;
  88092. y_end = header.height;
  88093. break;
  88094. case TGATools._ORIGIN_BR:
  88095. x_start = header.width - 1;
  88096. x_step = -1;
  88097. x_end = -1;
  88098. y_start = header.height - 1;
  88099. y_step = -1;
  88100. y_end = -1;
  88101. break;
  88102. }
  88103. // Load the specify method
  88104. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  88105. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  88106. var engine = texture.getEngine();
  88107. engine._uploadDataToTextureDirectly(texture, imageData);
  88108. };
  88109. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88110. var image = pixel_data, colormap = palettes;
  88111. var width = header.width, height = header.height;
  88112. var color, i = 0, x, y;
  88113. var imageData = new Uint8Array(width * height * 4);
  88114. for (y = y_start; y !== y_end; y += y_step) {
  88115. for (x = x_start; x !== x_end; x += x_step, i++) {
  88116. color = image[i];
  88117. imageData[(x + width * y) * 4 + 3] = 255;
  88118. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  88119. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  88120. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  88121. }
  88122. }
  88123. return imageData;
  88124. };
  88125. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88126. var image = pixel_data;
  88127. var width = header.width, height = header.height;
  88128. var color, i = 0, x, y;
  88129. var imageData = new Uint8Array(width * height * 4);
  88130. for (y = y_start; y !== y_end; y += y_step) {
  88131. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88132. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  88133. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  88134. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  88135. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  88136. imageData[(x + width * y) * 4 + 0] = r;
  88137. imageData[(x + width * y) * 4 + 1] = g;
  88138. imageData[(x + width * y) * 4 + 2] = b;
  88139. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  88140. }
  88141. }
  88142. return imageData;
  88143. };
  88144. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88145. var image = pixel_data;
  88146. var width = header.width, height = header.height;
  88147. var i = 0, x, y;
  88148. var imageData = new Uint8Array(width * height * 4);
  88149. for (y = y_start; y !== y_end; y += y_step) {
  88150. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  88151. imageData[(x + width * y) * 4 + 3] = 255;
  88152. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88153. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88154. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88155. }
  88156. }
  88157. return imageData;
  88158. };
  88159. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88160. var image = pixel_data;
  88161. var width = header.width, height = header.height;
  88162. var i = 0, x, y;
  88163. var imageData = new Uint8Array(width * height * 4);
  88164. for (y = y_start; y !== y_end; y += y_step) {
  88165. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  88166. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88167. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88168. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88169. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  88170. }
  88171. }
  88172. return imageData;
  88173. };
  88174. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88175. var image = pixel_data;
  88176. var width = header.width, height = header.height;
  88177. var color, i = 0, x, y;
  88178. var imageData = new Uint8Array(width * height * 4);
  88179. for (y = y_start; y !== y_end; y += y_step) {
  88180. for (x = x_start; x !== x_end; x += x_step, i++) {
  88181. color = image[i];
  88182. imageData[(x + width * y) * 4 + 0] = color;
  88183. imageData[(x + width * y) * 4 + 1] = color;
  88184. imageData[(x + width * y) * 4 + 2] = color;
  88185. imageData[(x + width * y) * 4 + 3] = 255;
  88186. }
  88187. }
  88188. return imageData;
  88189. };
  88190. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88191. var image = pixel_data;
  88192. var width = header.width, height = header.height;
  88193. var i = 0, x, y;
  88194. var imageData = new Uint8Array(width * height * 4);
  88195. for (y = y_start; y !== y_end; y += y_step) {
  88196. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88197. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  88198. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  88199. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88200. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  88201. }
  88202. }
  88203. return imageData;
  88204. };
  88205. //private static _TYPE_NO_DATA = 0;
  88206. TGATools._TYPE_INDEXED = 1;
  88207. TGATools._TYPE_RGB = 2;
  88208. TGATools._TYPE_GREY = 3;
  88209. TGATools._TYPE_RLE_INDEXED = 9;
  88210. TGATools._TYPE_RLE_RGB = 10;
  88211. TGATools._TYPE_RLE_GREY = 11;
  88212. TGATools._ORIGIN_MASK = 0x30;
  88213. TGATools._ORIGIN_SHIFT = 0x04;
  88214. TGATools._ORIGIN_BL = 0x00;
  88215. TGATools._ORIGIN_BR = 0x01;
  88216. TGATools._ORIGIN_UL = 0x02;
  88217. TGATools._ORIGIN_UR = 0x03;
  88218. return TGATools;
  88219. }());
  88220. BABYLON.TGATools = TGATools;
  88221. })(BABYLON || (BABYLON = {}));
  88222. //# sourceMappingURL=babylon.tga.js.map
  88223. var BABYLON;
  88224. (function (BABYLON) {
  88225. /**
  88226. * Implementation of the TGA Texture Loader.
  88227. */
  88228. var TGATextureLoader = /** @class */ (function () {
  88229. function TGATextureLoader() {
  88230. /**
  88231. * Defines wether the loader supports cascade loading the different faces.
  88232. */
  88233. this.supportCascades = false;
  88234. }
  88235. /**
  88236. * This returns if the loader support the current file information.
  88237. * @param extension defines the file extension of the file being loaded
  88238. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88239. * @param fallback defines the fallback internal texture if any
  88240. * @param isBase64 defines whether the texture is encoded as a base64
  88241. * @param isBuffer defines whether the texture data are stored as a buffer
  88242. * @returns true if the loader can load the specified file
  88243. */
  88244. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88245. return extension.indexOf(".tga") === 0;
  88246. };
  88247. /**
  88248. * Transform the url before loading if required.
  88249. * @param rootUrl the url of the texture
  88250. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88251. * @returns the transformed texture
  88252. */
  88253. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88254. return rootUrl;
  88255. };
  88256. /**
  88257. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88258. * @param rootUrl the url of the texture
  88259. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88260. * @returns the fallback texture
  88261. */
  88262. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88263. return null;
  88264. };
  88265. /**
  88266. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88267. * @param data contains the texture data
  88268. * @param texture defines the BabylonJS internal texture
  88269. * @param createPolynomials will be true if polynomials have been requested
  88270. * @param onLoad defines the callback to trigger once the texture is ready
  88271. * @param onError defines the callback to trigger in case of error
  88272. */
  88273. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88274. throw ".env not supported in Cube.";
  88275. };
  88276. /**
  88277. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88278. * @param data contains the texture data
  88279. * @param texture defines the BabylonJS internal texture
  88280. * @param callback defines the method to call once ready to upload
  88281. */
  88282. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  88283. var uintData = new Uint8Array(data);
  88284. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  88285. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  88286. BABYLON.TGATools.UploadContent(texture, uintData);
  88287. });
  88288. };
  88289. return TGATextureLoader;
  88290. }());
  88291. // Register the loader.
  88292. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  88293. })(BABYLON || (BABYLON = {}));
  88294. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  88295. var BABYLON;
  88296. (function (BABYLON) {
  88297. /**
  88298. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  88299. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  88300. */
  88301. var KhronosTextureContainer = /** @class */ (function () {
  88302. /**
  88303. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  88304. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  88305. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  88306. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  88307. */
  88308. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  88309. this.arrayBuffer = arrayBuffer;
  88310. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  88311. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  88312. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  88313. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  88314. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  88315. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  88316. BABYLON.Tools.Error("texture missing KTX identifier");
  88317. return;
  88318. }
  88319. // load the reset of the header in native 32 bit int
  88320. var header = new Int32Array(this.arrayBuffer, 12, 13);
  88321. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  88322. var oppositeEndianess = header[0] === 0x01020304;
  88323. // read all the header elements in order they exist in the file, without modification (sans endainness)
  88324. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  88325. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  88326. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  88327. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  88328. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  88329. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  88330. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  88331. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  88332. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  88333. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  88334. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  88335. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  88336. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  88337. if (this.glType !== 0) {
  88338. BABYLON.Tools.Error("only compressed formats currently supported");
  88339. return;
  88340. }
  88341. else {
  88342. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  88343. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  88344. }
  88345. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  88346. BABYLON.Tools.Error("only 2D textures currently supported");
  88347. return;
  88348. }
  88349. if (this.numberOfArrayElements !== 0) {
  88350. BABYLON.Tools.Error("texture arrays not currently supported");
  88351. return;
  88352. }
  88353. if (this.numberOfFaces !== facesExpected) {
  88354. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  88355. return;
  88356. }
  88357. // we now have a completely validated file, so could use existence of loadType as success
  88358. // would need to make this more elaborate & adjust checks above to support more than one load type
  88359. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  88360. }
  88361. // not as fast hardware based, but will probably never need to use
  88362. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  88363. return ((val & 0xFF) << 24)
  88364. | ((val & 0xFF00) << 8)
  88365. | ((val >> 8) & 0xFF00)
  88366. | ((val >> 24) & 0xFF);
  88367. };
  88368. /**
  88369. * Uploads KTX content to a Babylon Texture.
  88370. * It is assumed that the texture has already been created & is currently bound
  88371. * @hidden
  88372. */
  88373. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  88374. switch (this.loadType) {
  88375. case KhronosTextureContainer.COMPRESSED_2D:
  88376. this._upload2DCompressedLevels(texture, loadMipmaps);
  88377. break;
  88378. case KhronosTextureContainer.TEX_2D:
  88379. case KhronosTextureContainer.COMPRESSED_3D:
  88380. case KhronosTextureContainer.TEX_3D:
  88381. }
  88382. };
  88383. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  88384. // initialize width & height for level 1
  88385. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  88386. var width = this.pixelWidth;
  88387. var height = this.pixelHeight;
  88388. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  88389. for (var level = 0; level < mipmapCount; level++) {
  88390. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  88391. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  88392. for (var face = 0; face < this.numberOfFaces; face++) {
  88393. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  88394. var engine = texture.getEngine();
  88395. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  88396. dataOffset += imageSize; // add size of the image for the next face/mipmap
  88397. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  88398. }
  88399. width = Math.max(1.0, width * 0.5);
  88400. height = Math.max(1.0, height * 0.5);
  88401. }
  88402. };
  88403. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  88404. // load types
  88405. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  88406. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  88407. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  88408. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  88409. return KhronosTextureContainer;
  88410. }());
  88411. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  88412. })(BABYLON || (BABYLON = {}));
  88413. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  88414. var BABYLON;
  88415. (function (BABYLON) {
  88416. /**
  88417. * Implementation of the KTX Texture Loader.
  88418. */
  88419. var KTXTextureLoader = /** @class */ (function () {
  88420. function KTXTextureLoader() {
  88421. /**
  88422. * Defines wether the loader supports cascade loading the different faces.
  88423. */
  88424. this.supportCascades = false;
  88425. }
  88426. /**
  88427. * This returns if the loader support the current file information.
  88428. * @param extension defines the file extension of the file being loaded
  88429. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88430. * @param fallback defines the fallback internal texture if any
  88431. * @param isBase64 defines whether the texture is encoded as a base64
  88432. * @param isBuffer defines whether the texture data are stored as a buffer
  88433. * @returns true if the loader can load the specified file
  88434. */
  88435. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88436. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  88437. return true;
  88438. }
  88439. return false;
  88440. };
  88441. /**
  88442. * Transform the url before loading if required.
  88443. * @param rootUrl the url of the texture
  88444. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88445. * @returns the transformed texture
  88446. */
  88447. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88448. var lastDot = rootUrl.lastIndexOf('.');
  88449. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  88450. };
  88451. /**
  88452. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88453. * @param rootUrl the url of the texture
  88454. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88455. * @returns the fallback texture
  88456. */
  88457. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88458. // remove the format appended to the rootUrl in the original createCubeTexture call.
  88459. var exp = new RegExp("" + textureFormatInUse + "$");
  88460. return rootUrl.replace(exp, "");
  88461. };
  88462. /**
  88463. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88464. * @param data contains the texture data
  88465. * @param texture defines the BabylonJS internal texture
  88466. * @param createPolynomials will be true if polynomials have been requested
  88467. * @param onLoad defines the callback to trigger once the texture is ready
  88468. * @param onError defines the callback to trigger in case of error
  88469. */
  88470. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88471. if (Array.isArray(data)) {
  88472. return;
  88473. }
  88474. var engine = texture.getEngine();
  88475. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  88476. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  88477. engine._unpackFlipY(true);
  88478. ktx.uploadLevels(texture, texture.generateMipMaps);
  88479. texture.width = ktx.pixelWidth;
  88480. texture.height = ktx.pixelHeight;
  88481. engine._setCubeMapTextureParams(loadMipmap);
  88482. texture.isReady = true;
  88483. };
  88484. /**
  88485. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88486. * @param data contains the texture data
  88487. * @param texture defines the BabylonJS internal texture
  88488. * @param callback defines the method to call once ready to upload
  88489. */
  88490. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  88491. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  88492. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  88493. ktx.uploadLevels(texture, texture.generateMipMaps);
  88494. });
  88495. };
  88496. return KTXTextureLoader;
  88497. }());
  88498. // Register the loader.
  88499. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  88500. })(BABYLON || (BABYLON = {}));
  88501. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  88502. var BABYLON;
  88503. (function (BABYLON) {
  88504. /**
  88505. * Sets of helpers addressing the serialization and deserialization of environment texture
  88506. * stored in a BabylonJS env file.
  88507. * Those files are usually stored as .env files.
  88508. */
  88509. var EnvironmentTextureTools = /** @class */ (function () {
  88510. function EnvironmentTextureTools() {
  88511. }
  88512. /**
  88513. * Gets the environment info from an env file.
  88514. * @param data The array buffer containing the .env bytes.
  88515. * @returns the environment file info (the json header) if successfully parsed.
  88516. */
  88517. EnvironmentTextureTools.GetEnvInfo = function (data) {
  88518. var dataView = new DataView(data);
  88519. var pos = 0;
  88520. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88521. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  88522. BABYLON.Tools.Error('Not a babylon environment map');
  88523. return null;
  88524. }
  88525. }
  88526. // Read json manifest - collect characters up to null terminator
  88527. var manifestString = '';
  88528. var charCode = 0x00;
  88529. while ((charCode = dataView.getUint8(pos++))) {
  88530. manifestString += String.fromCharCode(charCode);
  88531. }
  88532. var manifest = JSON.parse(manifestString);
  88533. if (manifest.specular) {
  88534. // Extend the header with the position of the payload.
  88535. manifest.specular.specularDataPosition = pos;
  88536. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  88537. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  88538. }
  88539. return manifest;
  88540. };
  88541. /**
  88542. * Creates an environment texture from a loaded cube texture.
  88543. * @param texture defines the cube texture to convert in env file
  88544. * @return a promise containing the environment data if succesfull.
  88545. */
  88546. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  88547. var _this = this;
  88548. var internalTexture = texture.getInternalTexture();
  88549. if (!internalTexture) {
  88550. return Promise.reject("The cube texture is invalid.");
  88551. }
  88552. if (!texture._prefiltered) {
  88553. return Promise.reject("The cube texture is invalid (not prefiltered).");
  88554. }
  88555. var engine = internalTexture.getEngine();
  88556. if (engine && engine.premultipliedAlpha) {
  88557. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  88558. }
  88559. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  88560. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  88561. }
  88562. var canvas = engine.getRenderingCanvas();
  88563. if (!canvas) {
  88564. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  88565. }
  88566. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88567. if (!engine.getCaps().textureFloatRender) {
  88568. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88569. if (!engine.getCaps().textureHalfFloatRender) {
  88570. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  88571. }
  88572. }
  88573. var cubeWidth = internalTexture.width;
  88574. var hostingScene = new BABYLON.Scene(engine);
  88575. var specularTextures = {};
  88576. var promises = [];
  88577. // Read and collect all mipmaps data from the cube.
  88578. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  88579. mipmapsCount = Math.round(mipmapsCount);
  88580. var _loop_1 = function (i) {
  88581. var faceWidth = Math.pow(2, mipmapsCount - i);
  88582. var _loop_2 = function (face) {
  88583. var data = texture.readPixels(face, i);
  88584. // Creates a temp texture with the face data.
  88585. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  88586. // And rgbdEncode them.
  88587. var promise = new Promise(function (resolve, reject) {
  88588. 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);
  88589. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88590. rgbdPostProcess.onApply = function (effect) {
  88591. effect._bindTexture("textureSampler", tempTexture);
  88592. };
  88593. // As the process needs to happen on the main canvas, keep track of the current size
  88594. var currentW = engine.getRenderWidth();
  88595. var currentH = engine.getRenderHeight();
  88596. // Set the desired size for the texture
  88597. engine.setSize(faceWidth, faceWidth);
  88598. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  88599. // Reading datas from WebGL
  88600. BABYLON.Tools.ToBlob(canvas, function (blob) {
  88601. var fileReader = new FileReader();
  88602. fileReader.onload = function (event) {
  88603. var arrayBuffer = event.target.result;
  88604. specularTextures[i * 6 + face] = arrayBuffer;
  88605. resolve();
  88606. };
  88607. fileReader.readAsArrayBuffer(blob);
  88608. });
  88609. // Reapply the previous canvas size
  88610. engine.setSize(currentW, currentH);
  88611. });
  88612. });
  88613. promises.push(promise);
  88614. };
  88615. // All faces of the cube.
  88616. for (var face = 0; face < 6; face++) {
  88617. _loop_2(face);
  88618. }
  88619. };
  88620. for (var i = 0; i <= mipmapsCount; i++) {
  88621. _loop_1(i);
  88622. }
  88623. // Once all the textures haves been collected as RGBD stored in PNGs
  88624. return Promise.all(promises).then(function () {
  88625. // We can delete the hosting scene keeping track of all the creation objects
  88626. hostingScene.dispose();
  88627. // Creates the json header for the env texture
  88628. var info = {
  88629. version: 1,
  88630. width: cubeWidth,
  88631. irradiance: _this._CreateEnvTextureIrradiance(texture),
  88632. specular: {
  88633. mipmaps: [],
  88634. lodGenerationScale: texture.lodGenerationScale
  88635. }
  88636. };
  88637. // Sets the specular image data information
  88638. var position = 0;
  88639. for (var i = 0; i <= mipmapsCount; i++) {
  88640. for (var face = 0; face < 6; face++) {
  88641. var byteLength = specularTextures[i * 6 + face].byteLength;
  88642. info.specular.mipmaps.push({
  88643. length: byteLength,
  88644. position: position
  88645. });
  88646. position += byteLength;
  88647. }
  88648. }
  88649. // Encode the JSON as an array buffer
  88650. var infoString = JSON.stringify(info);
  88651. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  88652. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  88653. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  88654. infoView[i] = infoString.charCodeAt(i);
  88655. }
  88656. // Ends up with a null terminator for easier parsing
  88657. infoView[infoString.length] = 0x00;
  88658. // Computes the final required size and creates the storage
  88659. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  88660. var finalBuffer = new ArrayBuffer(totalSize);
  88661. var finalBufferView = new Uint8Array(finalBuffer);
  88662. var dataView = new DataView(finalBuffer);
  88663. // Copy the magic bytes identifying the file in
  88664. var pos = 0;
  88665. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88666. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  88667. }
  88668. // Add the json info
  88669. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  88670. pos += infoBuffer.byteLength;
  88671. // Finally inserts the texture data
  88672. for (var i = 0; i <= mipmapsCount; i++) {
  88673. for (var face = 0; face < 6; face++) {
  88674. var dataBuffer = specularTextures[i * 6 + face];
  88675. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  88676. pos += dataBuffer.byteLength;
  88677. }
  88678. }
  88679. // Voila
  88680. return finalBuffer;
  88681. });
  88682. };
  88683. /**
  88684. * Creates a JSON representation of the spherical data.
  88685. * @param texture defines the texture containing the polynomials
  88686. * @return the JSON representation of the spherical info
  88687. */
  88688. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  88689. var polynmials = texture.sphericalPolynomial;
  88690. if (polynmials == null) {
  88691. return null;
  88692. }
  88693. return {
  88694. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  88695. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  88696. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  88697. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  88698. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  88699. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  88700. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  88701. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  88702. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  88703. };
  88704. };
  88705. /**
  88706. * Uploads the texture info contained in the env file to the GPU.
  88707. * @param texture defines the internal texture to upload to
  88708. * @param arrayBuffer defines the buffer cotaining the data to load
  88709. * @param info defines the texture info retrieved through the GetEnvInfo method
  88710. * @returns a promise
  88711. */
  88712. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  88713. if (info.version !== 1) {
  88714. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  88715. }
  88716. var specularInfo = info.specular;
  88717. if (!specularInfo) {
  88718. // Nothing else parsed so far
  88719. return Promise.resolve();
  88720. }
  88721. // Double checks the enclosed info
  88722. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  88723. mipmapsCount = Math.round(mipmapsCount) + 1;
  88724. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  88725. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  88726. }
  88727. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  88728. var imageData = new Array(mipmapsCount);
  88729. for (var i = 0; i < mipmapsCount; i++) {
  88730. imageData[i] = new Array(6);
  88731. for (var face = 0; face < 6; face++) {
  88732. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  88733. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  88734. }
  88735. }
  88736. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  88737. };
  88738. /**
  88739. * Uploads the levels of image data to the GPU.
  88740. * @param texture defines the internal texture to upload to
  88741. * @param imageData defines the array buffer views of image data [mipmap][face]
  88742. * @returns a promise
  88743. */
  88744. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  88745. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  88746. throw new Error("Texture size must be a power of two");
  88747. }
  88748. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  88749. // Gets everything ready.
  88750. var engine = texture.getEngine();
  88751. var expandTexture = false;
  88752. var generateNonLODTextures = false;
  88753. var rgbdPostProcess = null;
  88754. var cubeRtt = null;
  88755. var lodTextures = null;
  88756. var caps = engine.getCaps();
  88757. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88758. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88759. texture.generateMipMaps = true;
  88760. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  88761. // Add extra process if texture lod is not supported
  88762. if (!caps.textureLOD) {
  88763. expandTexture = false;
  88764. generateNonLODTextures = true;
  88765. lodTextures = {};
  88766. }
  88767. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  88768. else if (engine.webGLVersion < 2) {
  88769. expandTexture = false;
  88770. }
  88771. // If half float available we can uncompress the texture
  88772. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  88773. expandTexture = true;
  88774. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88775. }
  88776. // If full float available we can uncompress the texture
  88777. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  88778. expandTexture = true;
  88779. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88780. }
  88781. // Expand the texture if possible
  88782. if (expandTexture) {
  88783. // Simply run through the decode PP
  88784. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  88785. texture._isRGBD = false;
  88786. texture.invertY = false;
  88787. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  88788. generateDepthBuffer: false,
  88789. generateMipMaps: true,
  88790. generateStencilBuffer: false,
  88791. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  88792. type: texture.type,
  88793. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  88794. });
  88795. }
  88796. else {
  88797. texture._isRGBD = true;
  88798. texture.invertY = true;
  88799. // In case of missing support, applies the same patch than DDS files.
  88800. if (generateNonLODTextures) {
  88801. var mipSlices = 3;
  88802. var scale = texture._lodGenerationScale;
  88803. var offset = texture._lodGenerationOffset;
  88804. for (var i = 0; i < mipSlices; i++) {
  88805. //compute LOD from even spacing in smoothness (matching shader calculation)
  88806. var smoothness = i / (mipSlices - 1);
  88807. var roughness = 1 - smoothness;
  88808. var minLODIndex = offset; // roughness = 0
  88809. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  88810. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  88811. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  88812. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  88813. glTextureFromLod.isCube = true;
  88814. glTextureFromLod.invertY = true;
  88815. glTextureFromLod.generateMipMaps = false;
  88816. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  88817. // Wrap in a base texture for easy binding.
  88818. var lodTexture = new BABYLON.BaseTexture(null);
  88819. lodTexture.isCube = true;
  88820. lodTexture._texture = glTextureFromLod;
  88821. lodTextures[mipmapIndex] = lodTexture;
  88822. switch (i) {
  88823. case 0:
  88824. texture._lodTextureLow = lodTexture;
  88825. break;
  88826. case 1:
  88827. texture._lodTextureMid = lodTexture;
  88828. break;
  88829. case 2:
  88830. texture._lodTextureHigh = lodTexture;
  88831. break;
  88832. }
  88833. }
  88834. }
  88835. }
  88836. var promises = [];
  88837. var _loop_3 = function (i) {
  88838. var _loop_4 = function (face) {
  88839. // Constructs an image element from image data
  88840. var bytes = imageData[i][face];
  88841. var blob = new Blob([bytes], { type: 'image/png' });
  88842. var url = URL.createObjectURL(blob);
  88843. var image = new Image();
  88844. image.src = url;
  88845. // Enqueue promise to upload to the texture.
  88846. var promise = new Promise(function (resolve, reject) {
  88847. image.onload = function () {
  88848. if (expandTexture) {
  88849. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  88850. reject(message);
  88851. }, image);
  88852. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88853. // Uncompress the data to a RTT
  88854. rgbdPostProcess.onApply = function (effect) {
  88855. effect._bindTexture("textureSampler", tempTexture_1);
  88856. effect.setFloat2("scale", 1, 1);
  88857. };
  88858. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  88859. // Cleanup
  88860. engine.restoreDefaultFramebuffer();
  88861. tempTexture_1.dispose();
  88862. window.URL.revokeObjectURL(url);
  88863. resolve();
  88864. });
  88865. }
  88866. else {
  88867. engine._uploadImageToTexture(texture, image, face, i);
  88868. // Upload the face to the non lod texture support
  88869. if (generateNonLODTextures) {
  88870. var lodTexture = lodTextures[i];
  88871. if (lodTexture) {
  88872. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  88873. }
  88874. }
  88875. resolve();
  88876. }
  88877. };
  88878. image.onerror = function (error) {
  88879. reject(error);
  88880. };
  88881. });
  88882. promises.push(promise);
  88883. };
  88884. // All faces
  88885. for (var face = 0; face < 6; face++) {
  88886. _loop_4(face);
  88887. }
  88888. };
  88889. // All mipmaps up to provided number of images
  88890. for (var i = 0; i < imageData.length; i++) {
  88891. _loop_3(i);
  88892. }
  88893. // Fill remaining mipmaps with black textures.
  88894. if (imageData.length < mipmapsCount) {
  88895. var data = void 0;
  88896. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  88897. var dataLength = size * size * 4;
  88898. switch (texture.type) {
  88899. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  88900. data = new Uint8Array(dataLength);
  88901. break;
  88902. }
  88903. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  88904. data = new Uint16Array(dataLength);
  88905. break;
  88906. }
  88907. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  88908. data = new Float32Array(dataLength);
  88909. break;
  88910. }
  88911. }
  88912. for (var i = imageData.length; i < mipmapsCount; i++) {
  88913. for (var face = 0; face < 6; face++) {
  88914. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  88915. }
  88916. }
  88917. }
  88918. // Once all done, finishes the cleanup and return
  88919. return Promise.all(promises).then(function () {
  88920. // Release temp RTT.
  88921. if (cubeRtt) {
  88922. engine._releaseFramebufferObjects(cubeRtt);
  88923. cubeRtt._swapAndDie(texture);
  88924. }
  88925. // Release temp Post Process.
  88926. if (rgbdPostProcess) {
  88927. rgbdPostProcess.dispose();
  88928. }
  88929. // Flag internal texture as ready in case they are in use.
  88930. if (generateNonLODTextures) {
  88931. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  88932. texture._lodTextureHigh._texture.isReady = true;
  88933. }
  88934. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  88935. texture._lodTextureMid._texture.isReady = true;
  88936. }
  88937. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  88938. texture._lodTextureLow._texture.isReady = true;
  88939. }
  88940. }
  88941. });
  88942. };
  88943. /**
  88944. * Uploads spherical polynomials information to the texture.
  88945. * @param texture defines the texture we are trying to upload the information to
  88946. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  88947. */
  88948. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  88949. if (info.version !== 1) {
  88950. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  88951. }
  88952. var irradianceInfo = info.irradiance;
  88953. if (!irradianceInfo) {
  88954. return;
  88955. }
  88956. var sp = new BABYLON.SphericalPolynomial();
  88957. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  88958. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  88959. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  88960. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  88961. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  88962. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  88963. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  88964. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  88965. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  88966. texture._sphericalPolynomial = sp;
  88967. };
  88968. /**
  88969. * Magic number identifying the env file.
  88970. */
  88971. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  88972. return EnvironmentTextureTools;
  88973. }());
  88974. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  88975. })(BABYLON || (BABYLON = {}));
  88976. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  88977. var BABYLON;
  88978. (function (BABYLON) {
  88979. /**
  88980. * Implementation of the ENV Texture Loader.
  88981. */
  88982. var ENVTextureLoader = /** @class */ (function () {
  88983. function ENVTextureLoader() {
  88984. /**
  88985. * Defines wether the loader supports cascade loading the different faces.
  88986. */
  88987. this.supportCascades = false;
  88988. }
  88989. /**
  88990. * This returns if the loader support the current file information.
  88991. * @param extension defines the file extension of the file being loaded
  88992. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88993. * @param fallback defines the fallback internal texture if any
  88994. * @param isBase64 defines whether the texture is encoded as a base64
  88995. * @param isBuffer defines whether the texture data are stored as a buffer
  88996. * @returns true if the loader can load the specified file
  88997. */
  88998. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88999. return extension.indexOf(".env") === 0;
  89000. };
  89001. /**
  89002. * Transform the url before loading if required.
  89003. * @param rootUrl the url of the texture
  89004. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89005. * @returns the transformed texture
  89006. */
  89007. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89008. return rootUrl;
  89009. };
  89010. /**
  89011. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89012. * @param rootUrl the url of the texture
  89013. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89014. * @returns the fallback texture
  89015. */
  89016. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89017. return null;
  89018. };
  89019. /**
  89020. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89021. * @param data contains the texture data
  89022. * @param texture defines the BabylonJS internal texture
  89023. * @param createPolynomials will be true if polynomials have been requested
  89024. * @param onLoad defines the callback to trigger once the texture is ready
  89025. * @param onError defines the callback to trigger in case of error
  89026. */
  89027. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89028. if (Array.isArray(data)) {
  89029. return;
  89030. }
  89031. data = data;
  89032. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  89033. if (info) {
  89034. texture.width = info.width;
  89035. texture.height = info.width;
  89036. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  89037. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  89038. texture.isReady = true;
  89039. if (onLoad) {
  89040. onLoad();
  89041. }
  89042. });
  89043. }
  89044. else if (onError) {
  89045. onError("Can not parse the environment file", null);
  89046. }
  89047. };
  89048. /**
  89049. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89050. * @param data contains the texture data
  89051. * @param texture defines the BabylonJS internal texture
  89052. * @param callback defines the method to call once ready to upload
  89053. */
  89054. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  89055. throw ".env not supported in 2d.";
  89056. };
  89057. return ENVTextureLoader;
  89058. }());
  89059. // Register the loader.
  89060. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  89061. })(BABYLON || (BABYLON = {}));
  89062. //# sourceMappingURL=babylon.envTextureLoader.js.map
  89063. var BABYLON;
  89064. (function (BABYLON) {
  89065. /**
  89066. * Renders a layer on top of an existing scene
  89067. */
  89068. var UtilityLayerRenderer = /** @class */ (function () {
  89069. /**
  89070. * Instantiates a UtilityLayerRenderer
  89071. * @param originalScene the original scene that will be rendered on top of
  89072. */
  89073. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  89074. var _this = this;
  89075. this.originalScene = originalScene;
  89076. this._pointerCaptures = {};
  89077. this._lastPointerEvents = {};
  89078. /**
  89079. * If the utility layer should automatically be rendered on top of existing scene
  89080. */
  89081. this.shouldRender = true;
  89082. /**
  89083. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  89084. */
  89085. this.onlyCheckPointerDownEvents = true;
  89086. /**
  89087. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  89088. */
  89089. this.processAllEvents = false;
  89090. /**
  89091. * Observable raised when the pointer move from the utility layer scene to the main scene
  89092. */
  89093. this.onPointerOutObservable = new BABYLON.Observable();
  89094. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  89095. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  89096. this.utilityLayerScene._allowPostProcessClear = false;
  89097. originalScene.getEngine().scenes.pop();
  89098. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  89099. this.utilityLayerScene.detachControl();
  89100. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  89101. if (!_this.processAllEvents) {
  89102. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  89103. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  89104. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  89105. return;
  89106. }
  89107. }
  89108. var pointerEvent = (prePointerInfo.event);
  89109. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  89110. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89111. return;
  89112. }
  89113. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  89114. if (!prePointerInfo.ray && utilityScenePick) {
  89115. prePointerInfo.ray = utilityScenePick.ray;
  89116. }
  89117. // always fire the prepointer oversvable
  89118. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  89119. // allow every non pointer down event to flow to the utility layer
  89120. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  89121. if (!prePointerInfo.skipOnPointerObservable) {
  89122. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89123. }
  89124. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  89125. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89126. }
  89127. return;
  89128. }
  89129. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  89130. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  89131. if (utilityScenePick && utilityScenePick.hit) {
  89132. if (!prePointerInfo.skipOnPointerObservable) {
  89133. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89134. }
  89135. prePointerInfo.skipOnPointerObservable = true;
  89136. }
  89137. }
  89138. else {
  89139. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  89140. var pointerEvent_1 = (prePointerInfo.event);
  89141. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  89142. if (originalScenePick && utilityScenePick) {
  89143. // No pick in utility scene
  89144. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  89145. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89146. // We touched an utility mesh present in the main scene
  89147. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89148. prePointerInfo.skipOnPointerObservable = true;
  89149. }
  89150. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89151. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  89152. }
  89153. }
  89154. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  89155. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  89156. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  89157. // If a previous utility layer set this, do not unset this
  89158. if (!prePointerInfo.skipOnPointerObservable) {
  89159. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  89160. }
  89161. }
  89162. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  89163. // We have a pick in both scenes but main is closer than utility
  89164. // We touched an utility mesh present in the main scene
  89165. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89166. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89167. prePointerInfo.skipOnPointerObservable = true;
  89168. }
  89169. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  89170. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  89171. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  89172. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  89173. }
  89174. }
  89175. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  89176. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  89177. }
  89178. }
  89179. }
  89180. });
  89181. // Render directly on top of existing scene without clearing
  89182. this.utilityLayerScene.autoClear = false;
  89183. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  89184. if (_this.shouldRender) {
  89185. _this.render();
  89186. }
  89187. });
  89188. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  89189. _this.dispose();
  89190. });
  89191. this._updateCamera();
  89192. }
  89193. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  89194. /**
  89195. * 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)
  89196. */
  89197. get: function () {
  89198. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  89199. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89200. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89201. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89202. });
  89203. }
  89204. return UtilityLayerRenderer._DefaultUtilityLayer;
  89205. },
  89206. enumerable: true,
  89207. configurable: true
  89208. });
  89209. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  89210. /**
  89211. * 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)
  89212. */
  89213. get: function () {
  89214. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  89215. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89216. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  89217. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89218. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89219. });
  89220. }
  89221. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  89222. },
  89223. enumerable: true,
  89224. configurable: true
  89225. });
  89226. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  89227. if (!prePointerInfo.skipOnPointerObservable) {
  89228. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  89229. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  89230. }
  89231. };
  89232. /**
  89233. * Renders the utility layers scene on top of the original scene
  89234. */
  89235. UtilityLayerRenderer.prototype.render = function () {
  89236. this._updateCamera();
  89237. if (this.utilityLayerScene.activeCamera) {
  89238. // Set the camera's scene to utility layers scene
  89239. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  89240. var camera = this.utilityLayerScene.activeCamera;
  89241. camera._scene = this.utilityLayerScene;
  89242. if (camera.leftCamera) {
  89243. camera.leftCamera._scene = this.utilityLayerScene;
  89244. }
  89245. if (camera.rightCamera) {
  89246. camera.rightCamera._scene = this.utilityLayerScene;
  89247. }
  89248. this.utilityLayerScene.render(false);
  89249. // Reset camera's scene back to original
  89250. camera._scene = oldScene;
  89251. if (camera.leftCamera) {
  89252. camera.leftCamera._scene = oldScene;
  89253. }
  89254. if (camera.rightCamera) {
  89255. camera.rightCamera._scene = oldScene;
  89256. }
  89257. }
  89258. };
  89259. /**
  89260. * Disposes of the renderer
  89261. */
  89262. UtilityLayerRenderer.prototype.dispose = function () {
  89263. this.onPointerOutObservable.clear();
  89264. if (this._afterRenderObserver) {
  89265. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  89266. }
  89267. if (this._sceneDisposeObserver) {
  89268. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89269. }
  89270. if (this._originalPointerObserver) {
  89271. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  89272. }
  89273. this.utilityLayerScene.dispose();
  89274. };
  89275. UtilityLayerRenderer.prototype._updateCamera = function () {
  89276. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  89277. };
  89278. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89279. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89280. return UtilityLayerRenderer;
  89281. }());
  89282. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  89283. })(BABYLON || (BABYLON = {}));
  89284. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  89285. //# sourceMappingURL=babylon.behavior.js.map
  89286. var BABYLON;
  89287. (function (BABYLON) {
  89288. /**
  89289. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  89290. */
  89291. var PointerDragBehavior = /** @class */ (function () {
  89292. /**
  89293. * Creates a pointer drag behavior that can be attached to a mesh
  89294. * @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)
  89295. */
  89296. function PointerDragBehavior(options) {
  89297. /**
  89298. * 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)
  89299. */
  89300. this.maxDragAngle = 0;
  89301. /**
  89302. * @hidden
  89303. */
  89304. this._useAlternatePickedPointAboveMaxDragAngle = false;
  89305. /**
  89306. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89307. */
  89308. this.currentDraggingPointerID = -1;
  89309. /**
  89310. * If the behavior is currently in a dragging state
  89311. */
  89312. this.dragging = false;
  89313. /**
  89314. * 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)
  89315. */
  89316. this.dragDeltaRatio = 0.2;
  89317. /**
  89318. * If the drag plane orientation should be updated during the dragging (Default: true)
  89319. */
  89320. this.updateDragPlane = true;
  89321. // Debug mode will display drag planes to help visualize behavior
  89322. this._debugMode = false;
  89323. this._moving = false;
  89324. /**
  89325. * Fires each time the attached mesh is dragged with the pointer
  89326. * * delta between last drag position and current drag position in world space
  89327. * * dragDistance along the drag axis
  89328. * * dragPlaneNormal normal of the current drag plane used during the drag
  89329. * * dragPlanePoint in world space where the drag intersects the drag plane
  89330. */
  89331. this.onDragObservable = new BABYLON.Observable();
  89332. /**
  89333. * Fires each time a drag begins (eg. mouse down on mesh)
  89334. */
  89335. this.onDragStartObservable = new BABYLON.Observable();
  89336. /**
  89337. * Fires each time a drag ends (eg. mouse release after drag)
  89338. */
  89339. this.onDragEndObservable = new BABYLON.Observable();
  89340. /**
  89341. * If the attached mesh should be moved when dragged
  89342. */
  89343. this.moveAttached = true;
  89344. /**
  89345. * If the drag behavior will react to drag events (Default: true)
  89346. */
  89347. this.enabled = true;
  89348. /**
  89349. * If camera controls should be detached during the drag
  89350. */
  89351. this.detachCameraControls = true;
  89352. /**
  89353. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  89354. */
  89355. this.useObjectOrienationForDragging = true;
  89356. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89357. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  89358. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  89359. // Variables to avoid instantiation in the below method
  89360. this._pointA = new BABYLON.Vector3(0, 0, 0);
  89361. this._pointB = new BABYLON.Vector3(0, 0, 0);
  89362. this._pointC = new BABYLON.Vector3(0, 0, 0);
  89363. this._lineA = new BABYLON.Vector3(0, 0, 0);
  89364. this._lineB = new BABYLON.Vector3(0, 0, 0);
  89365. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  89366. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  89367. this._options = options ? options : {};
  89368. var optionCount = 0;
  89369. if (this._options.dragAxis) {
  89370. optionCount++;
  89371. }
  89372. if (this._options.dragPlaneNormal) {
  89373. optionCount++;
  89374. }
  89375. if (optionCount > 1) {
  89376. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  89377. }
  89378. }
  89379. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  89380. /**
  89381. * The name of the behavior
  89382. */
  89383. get: function () {
  89384. return "PointerDrag";
  89385. },
  89386. enumerable: true,
  89387. configurable: true
  89388. });
  89389. /**
  89390. * Initializes the behavior
  89391. */
  89392. PointerDragBehavior.prototype.init = function () { };
  89393. /**
  89394. * Attaches the drag behavior the passed in mesh
  89395. * @param ownerNode The mesh that will be dragged around once attached
  89396. */
  89397. PointerDragBehavior.prototype.attach = function (ownerNode) {
  89398. var _this = this;
  89399. this._scene = ownerNode.getScene();
  89400. this._attachedNode = ownerNode;
  89401. // Initialize drag plane to not interfere with existing scene
  89402. if (!PointerDragBehavior._planeScene) {
  89403. if (this._debugMode) {
  89404. PointerDragBehavior._planeScene = this._scene;
  89405. }
  89406. else {
  89407. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  89408. PointerDragBehavior._planeScene.detachControl();
  89409. this._scene.getEngine().scenes.pop();
  89410. this._scene.onDisposeObservable.addOnce(function () {
  89411. PointerDragBehavior._planeScene.dispose();
  89412. PointerDragBehavior._planeScene = null;
  89413. });
  89414. }
  89415. }
  89416. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89417. // State of the drag
  89418. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  89419. var delta = new BABYLON.Vector3(0, 0, 0);
  89420. var dragLength = 0;
  89421. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  89422. var pickPredicate = function (m) {
  89423. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  89424. };
  89425. var attachedElement = null;
  89426. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89427. if (!_this.enabled) {
  89428. return;
  89429. }
  89430. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89431. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89432. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89433. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89434. if (pickedPoint) {
  89435. _this.dragging = true;
  89436. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89437. _this.lastDragPosition.copyFrom(pickedPoint);
  89438. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89439. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89440. // Detatch camera controls
  89441. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89442. if (_this._scene.activeCamera.inputs.attachedElement) {
  89443. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89444. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89445. }
  89446. else {
  89447. attachedElement = null;
  89448. }
  89449. }
  89450. }
  89451. }
  89452. }
  89453. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89454. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89455. _this.releaseDrag();
  89456. // Reattach camera controls
  89457. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89458. _this._scene.activeCamera.attachControl(attachedElement, true);
  89459. }
  89460. }
  89461. }
  89462. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89463. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89464. _this._moving = true;
  89465. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89466. if (pickedPoint) {
  89467. if (_this.updateDragPlane) {
  89468. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89469. }
  89470. // depending on the drag mode option drag accordingly
  89471. if (_this._options.dragAxis) {
  89472. // Convert local drag axis to world
  89473. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89474. // Project delta drag from the drag plane onto the drag axis
  89475. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89476. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89477. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89478. }
  89479. else {
  89480. dragLength = delta.length();
  89481. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89482. }
  89483. targetPosition.addInPlace(delta);
  89484. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89485. _this.lastDragPosition.copyFrom(pickedPoint);
  89486. }
  89487. }
  89488. }
  89489. });
  89490. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89491. if (_this._moving && _this.moveAttached) {
  89492. // Slowly move mesh to avoid jitter
  89493. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89494. _this._tmpVector.scaleInPlace(0.2);
  89495. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89496. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89497. }
  89498. });
  89499. };
  89500. PointerDragBehavior.prototype.releaseDrag = function () {
  89501. this.dragging = false;
  89502. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89503. this.currentDraggingPointerID = -1;
  89504. this._moving = false;
  89505. };
  89506. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89507. var _this = this;
  89508. if (!ray) {
  89509. return null;
  89510. }
  89511. // Calculate angle between plane normal and ray
  89512. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89513. // Correct if ray is casted from oposite side
  89514. if (angle > Math.PI / 2) {
  89515. angle = Math.PI - angle;
  89516. }
  89517. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  89518. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  89519. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  89520. // Invert ray direction along the towards object axis
  89521. this._tmpVector.copyFrom(ray.direction);
  89522. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  89523. this._alternatePickedPoint.normalize();
  89524. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  89525. this._tmpVector.addInPlace(this._alternatePickedPoint);
  89526. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  89527. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  89528. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  89529. this._alternatePickedPoint.addInPlace(this._tmpVector);
  89530. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  89531. return this._alternatePickedPoint;
  89532. }
  89533. else {
  89534. return null;
  89535. }
  89536. }
  89537. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89538. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89539. return pickResult.pickedPoint;
  89540. }
  89541. else {
  89542. return null;
  89543. }
  89544. };
  89545. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89546. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89547. this._pointA.copyFrom(dragPlanePosition);
  89548. if (this._options.dragAxis) {
  89549. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  89550. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89551. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89552. ray.origin.subtractToRef(this._pointA, this._pointC);
  89553. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89554. // Get perpendicular line from direction to camera and drag axis
  89555. this._pointB.subtractToRef(this._pointA, this._lineA);
  89556. this._pointC.subtractToRef(this._pointA, this._lineB);
  89557. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89558. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89559. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89560. this._lookAt.normalize();
  89561. this._dragPlane.position.copyFrom(this._pointA);
  89562. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89563. this._dragPlane.lookAt(this._lookAt);
  89564. }
  89565. else if (this._options.dragPlaneNormal) {
  89566. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  89567. this._dragPlane.position.copyFrom(this._pointA);
  89568. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89569. this._dragPlane.lookAt(this._lookAt);
  89570. }
  89571. else {
  89572. this._dragPlane.position.copyFrom(this._pointA);
  89573. this._dragPlane.lookAt(ray.origin);
  89574. }
  89575. this._dragPlane.computeWorldMatrix(true);
  89576. };
  89577. /**
  89578. * Detaches the behavior from the mesh
  89579. */
  89580. PointerDragBehavior.prototype.detach = function () {
  89581. if (this._pointerObserver) {
  89582. this._scene.onPointerObservable.remove(this._pointerObserver);
  89583. }
  89584. if (this._beforeRenderObserver) {
  89585. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89586. }
  89587. };
  89588. return PointerDragBehavior;
  89589. }());
  89590. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89591. })(BABYLON || (BABYLON = {}));
  89592. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89593. var BABYLON;
  89594. (function (BABYLON) {
  89595. /**
  89596. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89597. */
  89598. var MultiPointerScaleBehavior = /** @class */ (function () {
  89599. function MultiPointerScaleBehavior() {
  89600. this._startDistance = 0;
  89601. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89602. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89603. this._sceneRenderObserver = null;
  89604. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89605. this._dragBehaviorA.moveAttached = false;
  89606. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89607. this._dragBehaviorB.moveAttached = false;
  89608. }
  89609. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89610. /**
  89611. * The name of the behavior
  89612. */
  89613. get: function () {
  89614. return "MultiPointerScale";
  89615. },
  89616. enumerable: true,
  89617. configurable: true
  89618. });
  89619. /**
  89620. * Initializes the behavior
  89621. */
  89622. MultiPointerScaleBehavior.prototype.init = function () { };
  89623. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89624. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89625. };
  89626. /**
  89627. * Attaches the scale behavior the passed in mesh
  89628. * @param ownerNode The mesh that will be scaled around once attached
  89629. */
  89630. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89631. var _this = this;
  89632. this._ownerNode = ownerNode;
  89633. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89634. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89635. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89636. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89637. _this._dragBehaviorA.releaseDrag();
  89638. }
  89639. else {
  89640. _this._initialScale.copyFrom(ownerNode.scaling);
  89641. _this._startDistance = _this._getCurrentDistance();
  89642. }
  89643. }
  89644. });
  89645. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89646. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89647. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89648. _this._dragBehaviorB.releaseDrag();
  89649. }
  89650. else {
  89651. _this._initialScale.copyFrom(ownerNode.scaling);
  89652. _this._startDistance = _this._getCurrentDistance();
  89653. }
  89654. }
  89655. });
  89656. // Once both drag behaviors are active scale based on the distance between the two pointers
  89657. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89658. behavior.onDragObservable.add(function () {
  89659. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89660. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89661. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89662. }
  89663. });
  89664. });
  89665. ownerNode.addBehavior(this._dragBehaviorA);
  89666. ownerNode.addBehavior(this._dragBehaviorB);
  89667. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89668. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89669. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89670. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89671. if (change.length() > 0.01) {
  89672. ownerNode.scaling.addInPlace(change);
  89673. }
  89674. }
  89675. });
  89676. };
  89677. /**
  89678. * Detaches the behavior from the mesh
  89679. */
  89680. MultiPointerScaleBehavior.prototype.detach = function () {
  89681. var _this = this;
  89682. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89683. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89684. behavior.onDragStartObservable.clear();
  89685. behavior.onDragObservable.clear();
  89686. _this._ownerNode.removeBehavior(behavior);
  89687. });
  89688. };
  89689. return MultiPointerScaleBehavior;
  89690. }());
  89691. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89692. })(BABYLON || (BABYLON = {}));
  89693. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89694. var BABYLON;
  89695. (function (BABYLON) {
  89696. /**
  89697. * 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
  89698. */
  89699. var SixDofDragBehavior = /** @class */ (function () {
  89700. function SixDofDragBehavior() {
  89701. this._sceneRenderObserver = null;
  89702. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89703. this._moving = false;
  89704. this._startingOrientation = new BABYLON.Quaternion();
  89705. /**
  89706. * 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)
  89707. */
  89708. this.zDragFactor = 3;
  89709. /**
  89710. * If the behavior is currently in a dragging state
  89711. */
  89712. this.dragging = false;
  89713. /**
  89714. * 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)
  89715. */
  89716. this.dragDeltaRatio = 0.2;
  89717. /**
  89718. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89719. */
  89720. this.currentDraggingPointerID = -1;
  89721. /**
  89722. * If camera controls should be detached during the drag
  89723. */
  89724. this.detachCameraControls = true;
  89725. }
  89726. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89727. /**
  89728. * The name of the behavior
  89729. */
  89730. get: function () {
  89731. return "SixDofDrag";
  89732. },
  89733. enumerable: true,
  89734. configurable: true
  89735. });
  89736. /**
  89737. * Initializes the behavior
  89738. */
  89739. SixDofDragBehavior.prototype.init = function () { };
  89740. /**
  89741. * Attaches the scale behavior the passed in mesh
  89742. * @param ownerNode The mesh that will be scaled around once attached
  89743. */
  89744. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89745. var _this = this;
  89746. this._ownerNode = ownerNode;
  89747. this._scene = this._ownerNode.getScene();
  89748. if (!SixDofDragBehavior._virtualScene) {
  89749. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89750. this._scene.getEngine().scenes.pop();
  89751. }
  89752. var pickedMesh = null;
  89753. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89754. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89755. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89756. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89757. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89758. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89759. var pickPredicate = function (m) {
  89760. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89761. };
  89762. var attachedElement = null;
  89763. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89764. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89765. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89766. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89767. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89768. }
  89769. pickedMesh = _this._ownerNode;
  89770. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89771. // Set position and orientation of the controller
  89772. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89773. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89774. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89775. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89776. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89777. if (!pickedMesh.rotationQuaternion) {
  89778. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89779. }
  89780. var oldParent = pickedMesh.parent;
  89781. pickedMesh.setParent(null);
  89782. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89783. pickedMesh.setParent(oldParent);
  89784. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89785. // Update state
  89786. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89787. _this.dragging = true;
  89788. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89789. // Detatch camera controls
  89790. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89791. if (_this._scene.activeCamera.inputs.attachedElement) {
  89792. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89793. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89794. }
  89795. else {
  89796. attachedElement = null;
  89797. }
  89798. }
  89799. }
  89800. }
  89801. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89802. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89803. _this.dragging = false;
  89804. _this._moving = false;
  89805. _this.currentDraggingPointerID = -1;
  89806. pickedMesh = null;
  89807. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89808. // Reattach camera controls
  89809. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89810. _this._scene.activeCamera.attachControl(attachedElement, true);
  89811. }
  89812. }
  89813. }
  89814. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89815. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89816. var zDragFactor = _this.zDragFactor;
  89817. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89818. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89819. zDragFactor = 0;
  89820. }
  89821. // Calculate controller drag distance in controller space
  89822. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89823. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89824. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  89825. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89826. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89827. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  89828. if (_this._virtualDragMesh.position.z < 0) {
  89829. _this._virtualDragMesh.position.z = 0;
  89830. }
  89831. // Update the controller position
  89832. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89833. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89834. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89835. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89836. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89837. if (pickedMesh.parent) {
  89838. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89839. }
  89840. if (!_this._moving) {
  89841. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89842. }
  89843. _this._moving = true;
  89844. }
  89845. }
  89846. });
  89847. var tmpQuaternion = new BABYLON.Quaternion();
  89848. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89849. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89850. if (_this.dragging && _this._moving && pickedMesh) {
  89851. // Slowly move mesh to avoid jitter
  89852. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89853. // Get change in rotation
  89854. tmpQuaternion.copyFrom(_this._startingOrientation);
  89855. tmpQuaternion.x = -tmpQuaternion.x;
  89856. tmpQuaternion.y = -tmpQuaternion.y;
  89857. tmpQuaternion.z = -tmpQuaternion.z;
  89858. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89859. // Convert change in rotation to only y axis rotation
  89860. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89861. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89862. // Slowly move mesh to avoid jitter
  89863. var oldParent = pickedMesh.parent;
  89864. pickedMesh.setParent(null);
  89865. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89866. pickedMesh.setParent(oldParent);
  89867. }
  89868. });
  89869. };
  89870. /**
  89871. * Detaches the behavior from the mesh
  89872. */
  89873. SixDofDragBehavior.prototype.detach = function () {
  89874. if (this._scene) {
  89875. this._scene.onPointerObservable.remove(this._pointerObserver);
  89876. }
  89877. if (this._ownerNode) {
  89878. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89879. }
  89880. if (this._virtualOriginMesh) {
  89881. this._virtualOriginMesh.dispose();
  89882. }
  89883. if (this._virtualDragMesh) {
  89884. this._virtualDragMesh.dispose();
  89885. }
  89886. };
  89887. return SixDofDragBehavior;
  89888. }());
  89889. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89890. })(BABYLON || (BABYLON = {}));
  89891. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89892. var BABYLON;
  89893. (function (BABYLON) {
  89894. /**
  89895. * @hidden
  89896. */
  89897. var FaceDirectionInfo = /** @class */ (function () {
  89898. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  89899. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  89900. if (diff === void 0) { diff = 0; }
  89901. if (ignore === void 0) { ignore = false; }
  89902. this.direction = direction;
  89903. this.rotatedDirection = rotatedDirection;
  89904. this.diff = diff;
  89905. this.ignore = ignore;
  89906. }
  89907. return FaceDirectionInfo;
  89908. }());
  89909. /**
  89910. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  89911. */
  89912. var AttachToBoxBehavior = /** @class */ (function () {
  89913. /**
  89914. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  89915. * @param ui The transform node that should be attched to the mesh
  89916. */
  89917. function AttachToBoxBehavior(ui) {
  89918. this.ui = ui;
  89919. /**
  89920. * The name of the behavior
  89921. */
  89922. this.name = "AttachToBoxBehavior";
  89923. /**
  89924. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  89925. */
  89926. this.distanceAwayFromFace = 0.15;
  89927. /**
  89928. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  89929. */
  89930. this.distanceAwayFromBottomOfFace = 0.15;
  89931. 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))];
  89932. this._tmpMatrix = new BABYLON.Matrix();
  89933. this._tmpVector = new BABYLON.Vector3();
  89934. this._zeroVector = BABYLON.Vector3.Zero();
  89935. this._lookAtTmpMatrix = new BABYLON.Matrix();
  89936. /* Does nothing */
  89937. }
  89938. /**
  89939. * Initializes the behavior
  89940. */
  89941. AttachToBoxBehavior.prototype.init = function () {
  89942. /* Does nothing */
  89943. };
  89944. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  89945. var _this = this;
  89946. // Go over each face and calculate the angle between the face's normal and targetDirection
  89947. this._faceVectors.forEach(function (v) {
  89948. if (!_this._target.rotationQuaternion) {
  89949. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  89950. }
  89951. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  89952. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  89953. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  89954. });
  89955. // Return the face information of the one with the normal closeset to target direction
  89956. return this._faceVectors.reduce(function (min, p) {
  89957. if (min.ignore) {
  89958. return p;
  89959. }
  89960. else if (p.ignore) {
  89961. return min;
  89962. }
  89963. else {
  89964. return min.diff < p.diff ? min : p;
  89965. }
  89966. }, this._faceVectors[0]);
  89967. };
  89968. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  89969. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  89970. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  89971. this._lookAtTmpMatrix.invert();
  89972. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  89973. };
  89974. /**
  89975. * Attaches the AttachToBoxBehavior to the passed in mesh
  89976. * @param target The mesh that the specified node will be attached to
  89977. */
  89978. AttachToBoxBehavior.prototype.attach = function (target) {
  89979. var _this = this;
  89980. this._target = target;
  89981. this._scene = this._target.getScene();
  89982. // Every frame, update the app bars position
  89983. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89984. if (!_this._scene.activeCamera) {
  89985. return;
  89986. }
  89987. // Find the face closest to the cameras position
  89988. var cameraPos = _this._scene.activeCamera.position;
  89989. if (_this._scene.activeCamera.devicePosition) {
  89990. cameraPos = _this._scene.activeCamera.devicePosition;
  89991. }
  89992. var facing = _this._closestFace(cameraPos.subtract(target.position));
  89993. if (_this._scene.activeCamera.leftCamera) {
  89994. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89995. }
  89996. else {
  89997. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89998. }
  89999. // Get camera up direction
  90000. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  90001. // Ignore faces to not select a parrelel face for the up vector of the UI
  90002. _this._faceVectors.forEach(function (v) {
  90003. if (facing.direction.x && v.direction.x) {
  90004. v.ignore = true;
  90005. }
  90006. if (facing.direction.y && v.direction.y) {
  90007. v.ignore = true;
  90008. }
  90009. if (facing.direction.z && v.direction.z) {
  90010. v.ignore = true;
  90011. }
  90012. });
  90013. var facingUp = _this._closestFace(_this._tmpVector);
  90014. // Unignore faces
  90015. _this._faceVectors.forEach(function (v) {
  90016. v.ignore = false;
  90017. });
  90018. // Position the app bar on that face
  90019. _this.ui.position.copyFrom(target.position);
  90020. if (facing.direction.x) {
  90021. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90022. _this.ui.position.addInPlace(_this._tmpVector);
  90023. }
  90024. if (facing.direction.y) {
  90025. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90026. _this.ui.position.addInPlace(_this._tmpVector);
  90027. }
  90028. if (facing.direction.z) {
  90029. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90030. _this.ui.position.addInPlace(_this._tmpVector);
  90031. }
  90032. // Rotate to be oriented properly to the camera
  90033. if (!_this.ui.rotationQuaternion) {
  90034. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  90035. }
  90036. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  90037. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  90038. // Place ui the correct distance from the bottom of the mesh
  90039. if (facingUp.direction.x) {
  90040. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  90041. }
  90042. if (facingUp.direction.y) {
  90043. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  90044. }
  90045. if (facingUp.direction.z) {
  90046. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  90047. }
  90048. _this.ui.position.addInPlace(_this._tmpVector);
  90049. });
  90050. };
  90051. /**
  90052. * Detaches the behavior from the mesh
  90053. */
  90054. AttachToBoxBehavior.prototype.detach = function () {
  90055. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  90056. };
  90057. return AttachToBoxBehavior;
  90058. }());
  90059. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  90060. })(BABYLON || (BABYLON = {}));
  90061. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  90062. var BABYLON;
  90063. (function (BABYLON) {
  90064. /**
  90065. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  90066. */
  90067. var Gizmo = /** @class */ (function () {
  90068. /**
  90069. * Creates a gizmo
  90070. * @param gizmoLayer The utility layer the gizmo will be added to
  90071. */
  90072. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  90073. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90074. var _this = this;
  90075. this.gizmoLayer = gizmoLayer;
  90076. this._scaleFactor = 3;
  90077. this._tmpMatrix = new BABYLON.Matrix();
  90078. /**
  90079. * If a custom mesh has been set (Default: false)
  90080. */
  90081. this._customMeshSet = false;
  90082. /**
  90083. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  90084. */
  90085. this.updateGizmoRotationToMatchAttachedMesh = true;
  90086. /**
  90087. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  90088. */
  90089. this.updateGizmoPositionToMatchAttachedMesh = true;
  90090. /**
  90091. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  90092. */
  90093. this._updateScale = true;
  90094. this._interactionsEnabled = true;
  90095. this._tempVector = new BABYLON.Vector3();
  90096. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  90097. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  90098. _this._update();
  90099. });
  90100. this.attachedMesh = null;
  90101. }
  90102. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  90103. /**
  90104. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  90105. * * When set, interactions will be enabled
  90106. */
  90107. get: function () {
  90108. return this._attachedMesh;
  90109. },
  90110. set: function (value) {
  90111. this._attachedMesh = value;
  90112. this._rootMesh.setEnabled(value ? true : false);
  90113. this._attachedMeshChanged(value);
  90114. },
  90115. enumerable: true,
  90116. configurable: true
  90117. });
  90118. /**
  90119. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  90120. * @param mesh The mesh to replace the default mesh of the gizmo
  90121. */
  90122. Gizmo.prototype.setCustomMesh = function (mesh) {
  90123. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  90124. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  90125. }
  90126. this._rootMesh.getChildMeshes().forEach(function (c) {
  90127. c.dispose();
  90128. });
  90129. mesh.parent = this._rootMesh;
  90130. this._customMeshSet = true;
  90131. };
  90132. Gizmo.prototype._attachedMeshChanged = function (value) {
  90133. };
  90134. /**
  90135. * @hidden
  90136. * Updates the gizmo to match the attached mesh's position/rotation
  90137. */
  90138. Gizmo.prototype._update = function () {
  90139. if (this.attachedMesh) {
  90140. if (this.updateGizmoRotationToMatchAttachedMesh) {
  90141. if (!this._rootMesh.rotationQuaternion) {
  90142. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  90143. }
  90144. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  90145. this._tempVector.copyFrom(this.attachedMesh.scaling);
  90146. if (this.attachedMesh.scaling.x < 0) {
  90147. this.attachedMesh.scaling.x *= -1;
  90148. }
  90149. if (this.attachedMesh.scaling.y < 0) {
  90150. this.attachedMesh.scaling.y *= -1;
  90151. }
  90152. if (this.attachedMesh.scaling.z < 0) {
  90153. this.attachedMesh.scaling.z *= -1;
  90154. }
  90155. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  90156. this.attachedMesh.scaling.copyFrom(this._tempVector);
  90157. this.attachedMesh.computeWorldMatrix();
  90158. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  90159. }
  90160. if (this.updateGizmoPositionToMatchAttachedMesh) {
  90161. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  90162. }
  90163. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  90164. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  90165. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  90166. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  90167. }
  90168. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  90169. var dist = this._tempVector.length() / this._scaleFactor;
  90170. this._rootMesh.scaling.set(dist, dist, dist);
  90171. }
  90172. }
  90173. };
  90174. /**
  90175. * Disposes of the gizmo
  90176. */
  90177. Gizmo.prototype.dispose = function () {
  90178. this._rootMesh.dispose();
  90179. if (this._beforeRenderObserver) {
  90180. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90181. }
  90182. };
  90183. return Gizmo;
  90184. }());
  90185. BABYLON.Gizmo = Gizmo;
  90186. })(BABYLON || (BABYLON = {}));
  90187. //# sourceMappingURL=babylon.gizmo.js.map
  90188. var BABYLON;
  90189. (function (BABYLON) {
  90190. /**
  90191. * Single axis drag gizmo
  90192. */
  90193. var AxisDragGizmo = /** @class */ (function (_super) {
  90194. __extends(AxisDragGizmo, _super);
  90195. /**
  90196. * Creates an AxisDragGizmo
  90197. * @param gizmoLayer The utility layer the gizmo will be added to
  90198. * @param dragAxis The axis which the gizmo will be able to drag on
  90199. * @param color The color of the gizmo
  90200. */
  90201. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  90202. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90203. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90204. var _this = _super.call(this, gizmoLayer) || this;
  90205. _this._pointerObserver = null;
  90206. /**
  90207. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90208. */
  90209. _this.snapDistance = 0;
  90210. /**
  90211. * Event that fires each time the gizmo snaps to a new location.
  90212. * * snapDistance is the the change in distance
  90213. */
  90214. _this.onSnapObservable = new BABYLON.Observable();
  90215. // Create Material
  90216. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90217. coloredMaterial.disableLighting = true;
  90218. coloredMaterial.emissiveColor = color;
  90219. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90220. hoverMaterial.disableLighting = true;
  90221. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90222. // Build mesh on root node
  90223. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90224. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90225. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  90226. arrowTail.color = coloredMaterial.emissiveColor;
  90227. arrow.addChild(arrowMesh);
  90228. arrow.addChild(arrowTail);
  90229. // Position arrow pointing in its drag axis
  90230. arrowMesh.scaling.scaleInPlace(0.05);
  90231. arrowMesh.material = coloredMaterial;
  90232. arrowMesh.rotation.x = Math.PI / 2;
  90233. arrowMesh.position.z += 0.3;
  90234. arrowTail.scaling.scaleInPlace(0.2);
  90235. arrowTail.rotation.x = Math.PI / 2;
  90236. arrowTail.material = coloredMaterial;
  90237. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90238. _this._rootMesh.addChild(arrow);
  90239. var currentSnapDragDistance = 0;
  90240. var tmpVector = new BABYLON.Vector3();
  90241. var tmpSnapEvent = { snapDistance: 0 };
  90242. // Add drag behavior to handle events when the gizmo is dragged
  90243. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90244. _this.dragBehavior.moveAttached = false;
  90245. _this._rootMesh.addBehavior(_this.dragBehavior);
  90246. _this.dragBehavior.onDragObservable.add(function (event) {
  90247. if (_this.attachedMesh) {
  90248. // Snapping logic
  90249. if (_this.snapDistance == 0) {
  90250. _this.attachedMesh.position.addInPlace(event.delta);
  90251. }
  90252. else {
  90253. currentSnapDragDistance += event.dragDistance;
  90254. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90255. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  90256. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90257. event.delta.normalizeToRef(tmpVector);
  90258. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  90259. _this.attachedMesh.position.addInPlace(tmpVector);
  90260. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90261. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90262. }
  90263. }
  90264. }
  90265. });
  90266. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90267. if (_this._customMeshSet) {
  90268. return;
  90269. }
  90270. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90271. var material = isHovered ? hoverMaterial : coloredMaterial;
  90272. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90273. m.material = material;
  90274. if (m.color) {
  90275. m.color = material.emissiveColor;
  90276. }
  90277. });
  90278. });
  90279. return _this;
  90280. }
  90281. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  90282. if (this.dragBehavior) {
  90283. this.dragBehavior.enabled = value ? true : false;
  90284. }
  90285. };
  90286. /**
  90287. * Disposes of the gizmo
  90288. */
  90289. AxisDragGizmo.prototype.dispose = function () {
  90290. this.onSnapObservable.clear();
  90291. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90292. this.dragBehavior.detach();
  90293. _super.prototype.dispose.call(this);
  90294. };
  90295. return AxisDragGizmo;
  90296. }(BABYLON.Gizmo));
  90297. BABYLON.AxisDragGizmo = AxisDragGizmo;
  90298. })(BABYLON || (BABYLON = {}));
  90299. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  90300. var BABYLON;
  90301. (function (BABYLON) {
  90302. /**
  90303. * Single axis scale gizmo
  90304. */
  90305. var AxisScaleGizmo = /** @class */ (function (_super) {
  90306. __extends(AxisScaleGizmo, _super);
  90307. /**
  90308. * Creates an AxisScaleGizmo
  90309. * @param gizmoLayer The utility layer the gizmo will be added to
  90310. * @param dragAxis The axis which the gizmo will be able to scale on
  90311. * @param color The color of the gizmo
  90312. */
  90313. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  90314. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90315. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90316. var _this = _super.call(this, gizmoLayer) || this;
  90317. _this._pointerObserver = null;
  90318. /**
  90319. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90320. */
  90321. _this.snapDistance = 0;
  90322. /**
  90323. * Event that fires each time the gizmo snaps to a new location.
  90324. * * snapDistance is the the change in distance
  90325. */
  90326. _this.onSnapObservable = new BABYLON.Observable();
  90327. // Create Material
  90328. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90329. coloredMaterial.disableLighting = true;
  90330. coloredMaterial.emissiveColor = color;
  90331. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90332. hoverMaterial.disableLighting = true;
  90333. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90334. // Build mesh on root node
  90335. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90336. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  90337. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  90338. arrowTail.color = coloredMaterial.emissiveColor;
  90339. arrow.addChild(arrowMesh);
  90340. arrow.addChild(arrowTail);
  90341. // Position arrow pointing in its drag axis
  90342. arrowMesh.scaling.scaleInPlace(0.1);
  90343. arrowMesh.material = coloredMaterial;
  90344. arrowMesh.rotation.x = Math.PI / 2;
  90345. arrowMesh.position.z += 0.3;
  90346. arrowTail.scaling.scaleInPlace(0.2);
  90347. arrowTail.rotation.x = Math.PI / 2;
  90348. arrowTail.material = coloredMaterial;
  90349. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90350. _this._rootMesh.addChild(arrow);
  90351. // Add drag behavior to handle events when the gizmo is dragged
  90352. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90353. _this.dragBehavior.moveAttached = false;
  90354. _this._rootMesh.addBehavior(_this.dragBehavior);
  90355. var currentSnapDragDistance = 0;
  90356. var tmpVector = new BABYLON.Vector3();
  90357. var tmpSnapEvent = { snapDistance: 0 };
  90358. _this.dragBehavior.onDragObservable.add(function (event) {
  90359. if (_this.attachedMesh) {
  90360. // Snapping logic
  90361. var snapped = false;
  90362. var dragSteps = 0;
  90363. if (_this.snapDistance == 0) {
  90364. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  90365. }
  90366. else {
  90367. currentSnapDragDistance += event.dragDistance;
  90368. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90369. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90370. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90371. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  90372. snapped = true;
  90373. }
  90374. else {
  90375. tmpVector.scaleInPlace(0);
  90376. }
  90377. }
  90378. _this.attachedMesh.scaling.addInPlace(tmpVector);
  90379. if (snapped) {
  90380. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90381. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90382. }
  90383. }
  90384. });
  90385. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90386. if (_this._customMeshSet) {
  90387. return;
  90388. }
  90389. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90390. var material = isHovered ? hoverMaterial : coloredMaterial;
  90391. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90392. m.material = material;
  90393. if (m.color) {
  90394. m.color = material.emissiveColor;
  90395. }
  90396. });
  90397. });
  90398. return _this;
  90399. }
  90400. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  90401. if (this.dragBehavior) {
  90402. this.dragBehavior.enabled = value ? true : false;
  90403. }
  90404. };
  90405. /**
  90406. * Disposes of the gizmo
  90407. */
  90408. AxisScaleGizmo.prototype.dispose = function () {
  90409. this.onSnapObservable.clear();
  90410. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90411. this.dragBehavior.detach();
  90412. _super.prototype.dispose.call(this);
  90413. };
  90414. return AxisScaleGizmo;
  90415. }(BABYLON.Gizmo));
  90416. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  90417. })(BABYLON || (BABYLON = {}));
  90418. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  90419. var BABYLON;
  90420. (function (BABYLON) {
  90421. /**
  90422. * Single plane rotation gizmo
  90423. */
  90424. var PlaneRotationGizmo = /** @class */ (function (_super) {
  90425. __extends(PlaneRotationGizmo, _super);
  90426. /**
  90427. * Creates a PlaneRotationGizmo
  90428. * @param gizmoLayer The utility layer the gizmo will be added to
  90429. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  90430. * @param color The color of the gizmo
  90431. */
  90432. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  90433. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90434. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90435. var _this = _super.call(this, gizmoLayer) || this;
  90436. _this._pointerObserver = null;
  90437. /**
  90438. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  90439. */
  90440. _this.snapDistance = 0;
  90441. /**
  90442. * Event that fires each time the gizmo snaps to a new location.
  90443. * * snapDistance is the the change in distance
  90444. */
  90445. _this.onSnapObservable = new BABYLON.Observable();
  90446. // Create Material
  90447. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90448. coloredMaterial.disableLighting = true;
  90449. coloredMaterial.emissiveColor = color;
  90450. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90451. hoverMaterial.disableLighting = true;
  90452. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90453. // Build mesh on root node
  90454. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90455. // Create circle out of lines
  90456. var tessellation = 20;
  90457. var radius = 2;
  90458. var points = new Array();
  90459. for (var i = 0; i < tessellation; i++) {
  90460. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  90461. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  90462. }
  90463. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  90464. rotationMesh.color = coloredMaterial.emissiveColor;
  90465. // Position arrow pointing in its drag axis
  90466. rotationMesh.scaling.scaleInPlace(0.1);
  90467. rotationMesh.material = coloredMaterial;
  90468. rotationMesh.rotation.x = Math.PI / 2;
  90469. parentMesh.addChild(rotationMesh);
  90470. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  90471. _this._rootMesh.addChild(parentMesh);
  90472. // Add drag behavior to handle events when the gizmo is dragged
  90473. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  90474. _this.dragBehavior.moveAttached = false;
  90475. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  90476. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  90477. _this._rootMesh.addBehavior(_this.dragBehavior);
  90478. var lastDragPosition = new BABYLON.Vector3();
  90479. _this.dragBehavior.onDragStartObservable.add(function (e) {
  90480. if (_this.attachedMesh) {
  90481. lastDragPosition.copyFrom(e.dragPlanePoint);
  90482. }
  90483. });
  90484. var rotationMatrix = new BABYLON.Matrix();
  90485. var planeNormalTowardsCamera = new BABYLON.Vector3();
  90486. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  90487. var tmpSnapEvent = { snapDistance: 0 };
  90488. var currentSnapDragDistance = 0;
  90489. _this.dragBehavior.onDragObservable.add(function (event) {
  90490. if (_this.attachedMesh) {
  90491. if (!_this.attachedMesh.rotationQuaternion) {
  90492. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90493. }
  90494. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  90495. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  90496. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  90497. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  90498. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  90499. var angle = Math.atan2(cross.length(), dot);
  90500. planeNormalTowardsCamera.copyFrom(planeNormal);
  90501. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  90502. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90503. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  90504. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  90505. }
  90506. // Flip up vector depending on which side the camera is on
  90507. if (gizmoLayer.utilityLayerScene.activeCamera) {
  90508. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  90509. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  90510. planeNormalTowardsCamera.scaleInPlace(-1);
  90511. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  90512. }
  90513. }
  90514. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  90515. if (halfCircleSide)
  90516. angle = -angle;
  90517. // Snapping logic
  90518. var snapped = false;
  90519. if (_this.snapDistance != 0) {
  90520. currentSnapDragDistance += angle;
  90521. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90522. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90523. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90524. angle = _this.snapDistance * dragSteps;
  90525. snapped = true;
  90526. }
  90527. else {
  90528. angle = 0;
  90529. }
  90530. }
  90531. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  90532. var quaternionCoefficient = Math.sin(angle / 2);
  90533. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  90534. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90535. // Rotate selected mesh quaternion over fixed axis
  90536. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  90537. }
  90538. else {
  90539. // Rotate selected mesh quaternion over rotated axis
  90540. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  90541. }
  90542. lastDragPosition.copyFrom(event.dragPlanePoint);
  90543. if (snapped) {
  90544. tmpSnapEvent.snapDistance = angle;
  90545. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90546. }
  90547. }
  90548. });
  90549. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90550. if (_this._customMeshSet) {
  90551. return;
  90552. }
  90553. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90554. var material = isHovered ? hoverMaterial : coloredMaterial;
  90555. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90556. m.material = material;
  90557. if (m.color) {
  90558. m.color = material.emissiveColor;
  90559. }
  90560. });
  90561. });
  90562. return _this;
  90563. }
  90564. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  90565. if (this.dragBehavior) {
  90566. this.dragBehavior.enabled = value ? true : false;
  90567. }
  90568. };
  90569. /**
  90570. * Disposes of the gizmo
  90571. */
  90572. PlaneRotationGizmo.prototype.dispose = function () {
  90573. this.onSnapObservable.clear();
  90574. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90575. this.dragBehavior.detach();
  90576. _super.prototype.dispose.call(this);
  90577. };
  90578. return PlaneRotationGizmo;
  90579. }(BABYLON.Gizmo));
  90580. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  90581. })(BABYLON || (BABYLON = {}));
  90582. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  90583. var BABYLON;
  90584. (function (BABYLON) {
  90585. /**
  90586. * Gizmo that enables dragging a mesh along 3 axis
  90587. */
  90588. var PositionGizmo = /** @class */ (function (_super) {
  90589. __extends(PositionGizmo, _super);
  90590. /**
  90591. * Creates a PositionGizmo
  90592. * @param gizmoLayer The utility layer the gizmo will be added to
  90593. */
  90594. function PositionGizmo(gizmoLayer) {
  90595. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90596. var _this = _super.call(this, gizmoLayer) || this;
  90597. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90598. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90599. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90600. _this.attachedMesh = null;
  90601. return _this;
  90602. }
  90603. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  90604. set: function (mesh) {
  90605. if (this.xGizmo) {
  90606. this.xGizmo.attachedMesh = mesh;
  90607. this.yGizmo.attachedMesh = mesh;
  90608. this.zGizmo.attachedMesh = mesh;
  90609. }
  90610. },
  90611. enumerable: true,
  90612. configurable: true
  90613. });
  90614. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90615. get: function () {
  90616. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90617. },
  90618. set: function (value) {
  90619. if (this.xGizmo) {
  90620. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90621. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90622. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90623. }
  90624. },
  90625. enumerable: true,
  90626. configurable: true
  90627. });
  90628. /**
  90629. * Disposes of the gizmo
  90630. */
  90631. PositionGizmo.prototype.dispose = function () {
  90632. this.xGizmo.dispose();
  90633. this.yGizmo.dispose();
  90634. this.zGizmo.dispose();
  90635. };
  90636. /**
  90637. * CustomMeshes are not supported by this gizmo
  90638. * @param mesh The mesh to replace the default mesh of the gizmo
  90639. */
  90640. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  90641. 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)");
  90642. };
  90643. return PositionGizmo;
  90644. }(BABYLON.Gizmo));
  90645. BABYLON.PositionGizmo = PositionGizmo;
  90646. })(BABYLON || (BABYLON = {}));
  90647. //# sourceMappingURL=babylon.positionGizmo.js.map
  90648. var BABYLON;
  90649. (function (BABYLON) {
  90650. /**
  90651. * Gizmo that enables rotating a mesh along 3 axis
  90652. */
  90653. var RotationGizmo = /** @class */ (function (_super) {
  90654. __extends(RotationGizmo, _super);
  90655. /**
  90656. * Creates a RotationGizmo
  90657. * @param gizmoLayer The utility layer the gizmo will be added to
  90658. */
  90659. function RotationGizmo(gizmoLayer) {
  90660. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90661. var _this = _super.call(this, gizmoLayer) || this;
  90662. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90663. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90664. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90665. _this.attachedMesh = null;
  90666. return _this;
  90667. }
  90668. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  90669. set: function (mesh) {
  90670. if (this.xGizmo) {
  90671. this.xGizmo.attachedMesh = mesh;
  90672. this.yGizmo.attachedMesh = mesh;
  90673. this.zGizmo.attachedMesh = mesh;
  90674. }
  90675. },
  90676. enumerable: true,
  90677. configurable: true
  90678. });
  90679. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90680. get: function () {
  90681. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90682. },
  90683. set: function (value) {
  90684. if (this.xGizmo) {
  90685. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90686. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90687. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90688. }
  90689. },
  90690. enumerable: true,
  90691. configurable: true
  90692. });
  90693. /**
  90694. * Disposes of the gizmo
  90695. */
  90696. RotationGizmo.prototype.dispose = function () {
  90697. this.xGizmo.dispose();
  90698. this.yGizmo.dispose();
  90699. this.zGizmo.dispose();
  90700. };
  90701. /**
  90702. * CustomMeshes are not supported by this gizmo
  90703. * @param mesh The mesh to replace the default mesh of the gizmo
  90704. */
  90705. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  90706. 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)");
  90707. };
  90708. return RotationGizmo;
  90709. }(BABYLON.Gizmo));
  90710. BABYLON.RotationGizmo = RotationGizmo;
  90711. })(BABYLON || (BABYLON = {}));
  90712. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90713. var BABYLON;
  90714. (function (BABYLON) {
  90715. /**
  90716. * Gizmo that enables scaling a mesh along 3 axis
  90717. */
  90718. var ScaleGizmo = /** @class */ (function (_super) {
  90719. __extends(ScaleGizmo, _super);
  90720. /**
  90721. * Creates a ScaleGizmo
  90722. * @param gizmoLayer The utility layer the gizmo will be added to
  90723. */
  90724. function ScaleGizmo(gizmoLayer) {
  90725. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90726. var _this = _super.call(this, gizmoLayer) || this;
  90727. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90728. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90729. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90730. _this.attachedMesh = null;
  90731. return _this;
  90732. }
  90733. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90734. set: function (mesh) {
  90735. if (this.xGizmo) {
  90736. this.xGizmo.attachedMesh = mesh;
  90737. this.yGizmo.attachedMesh = mesh;
  90738. this.zGizmo.attachedMesh = mesh;
  90739. }
  90740. },
  90741. enumerable: true,
  90742. configurable: true
  90743. });
  90744. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90745. get: function () {
  90746. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90747. },
  90748. set: function (value) {
  90749. if (this.xGizmo) {
  90750. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90751. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90752. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90753. }
  90754. },
  90755. enumerable: true,
  90756. configurable: true
  90757. });
  90758. /**
  90759. * Disposes of the gizmo
  90760. */
  90761. ScaleGizmo.prototype.dispose = function () {
  90762. this.xGizmo.dispose();
  90763. this.yGizmo.dispose();
  90764. this.zGizmo.dispose();
  90765. };
  90766. return ScaleGizmo;
  90767. }(BABYLON.Gizmo));
  90768. BABYLON.ScaleGizmo = ScaleGizmo;
  90769. })(BABYLON || (BABYLON = {}));
  90770. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90771. var BABYLON;
  90772. (function (BABYLON) {
  90773. /**
  90774. * Bounding box gizmo
  90775. */
  90776. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90777. __extends(BoundingBoxGizmo, _super);
  90778. /**
  90779. * Creates an BoundingBoxGizmo
  90780. * @param gizmoLayer The utility layer the gizmo will be added to
  90781. * @param color The color of the gizmo
  90782. */
  90783. function BoundingBoxGizmo(color, gizmoLayer) {
  90784. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90785. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  90786. var _this = _super.call(this, gizmoLayer) || this;
  90787. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90788. _this._renderObserver = null;
  90789. _this._pointerObserver = null;
  90790. _this._scaleDragSpeed = 0.2;
  90791. _this._tmpQuaternion = new BABYLON.Quaternion();
  90792. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90793. /**
  90794. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90795. */
  90796. _this.rotationSphereSize = 0.1;
  90797. /**
  90798. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90799. */
  90800. _this.scaleBoxSize = 0.1;
  90801. /**
  90802. * 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)
  90803. */
  90804. _this.fixedDragMeshScreenSize = false;
  90805. /**
  90806. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90807. */
  90808. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90809. /**
  90810. * Fired when a rotation sphere or scale box is dragged
  90811. */
  90812. _this.onDragStartObservable = new BABYLON.Observable();
  90813. /**
  90814. * Fired when a rotation sphere or scale box drag is started
  90815. */
  90816. _this.onDragObservable = new BABYLON.Observable();
  90817. /**
  90818. * Fired when a rotation sphere or scale box drag is needed
  90819. */
  90820. _this.onDragEndObservable = new BABYLON.Observable();
  90821. _this._existingMeshScale = new BABYLON.Vector3();
  90822. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90823. _this._updateScale = false;
  90824. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  90825. // Create Materials
  90826. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90827. coloredMaterial.disableLighting = true;
  90828. coloredMaterial.emissiveColor = color;
  90829. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90830. hoverColoredMaterial.disableLighting = true;
  90831. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90832. // Build bounding box out of lines
  90833. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90834. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90835. var lines = [];
  90836. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90837. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90838. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90839. 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));
  90840. 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));
  90841. 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));
  90842. 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));
  90843. 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));
  90844. 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));
  90845. 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));
  90846. 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));
  90847. 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));
  90848. lines.forEach(function (l) {
  90849. l.color = color;
  90850. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90851. l.isPickable = false;
  90852. _this._lineBoundingBox.addChild(l);
  90853. });
  90854. _this._rootMesh.addChild(_this._lineBoundingBox);
  90855. // Create rotation spheres
  90856. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90857. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90858. var _loop_1 = function (i_1) {
  90859. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90860. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90861. sphere.material = coloredMaterial;
  90862. // Drag behavior
  90863. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90864. _dragBehavior.moveAttached = false;
  90865. _dragBehavior.updateDragPlane = false;
  90866. sphere.addBehavior(_dragBehavior);
  90867. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90868. var totalTurnAmountOfDrag = 0;
  90869. _dragBehavior.onDragStartObservable.add(function (event) {
  90870. startingTurnDirection.copyFrom(sphere.forward);
  90871. totalTurnAmountOfDrag = 0;
  90872. });
  90873. _dragBehavior.onDragObservable.add(function (event) {
  90874. _this.onDragObservable.notifyObservers({});
  90875. if (_this.attachedMesh) {
  90876. var worldDragDirection = startingTurnDirection;
  90877. // Project the world right on to the drag plane
  90878. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90879. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90880. // project drag delta on to the resulting drag axis and rotate based on that
  90881. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90882. // Make rotation relative to size of mesh.
  90883. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  90884. // Rotate based on axis
  90885. if (!_this.attachedMesh.rotationQuaternion) {
  90886. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90887. }
  90888. if (!_this._anchorMesh.rotationQuaternion) {
  90889. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  90890. }
  90891. // Do not allow the object to turn more than a full circle
  90892. totalTurnAmountOfDrag += projectDist;
  90893. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90894. if (i_1 >= 8) {
  90895. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90896. }
  90897. else if (i_1 >= 4) {
  90898. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90899. }
  90900. else {
  90901. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90902. }
  90903. // Rotate around center of bounding box
  90904. _this._anchorMesh.addChild(_this.attachedMesh);
  90905. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  90906. _this._anchorMesh.removeChild(_this.attachedMesh);
  90907. }
  90908. _this.updateBoundingBox();
  90909. }
  90910. });
  90911. // Selection/deselection
  90912. _dragBehavior.onDragStartObservable.add(function () {
  90913. _this.onDragStartObservable.notifyObservers({});
  90914. _this._selectNode(sphere);
  90915. });
  90916. _dragBehavior.onDragEndObservable.add(function () {
  90917. _this.onDragEndObservable.notifyObservers({});
  90918. _this._selectNode(null);
  90919. });
  90920. this_1._rotateSpheresParent.addChild(sphere);
  90921. };
  90922. var this_1 = this, _dragBehavior;
  90923. for (var i_1 = 0; i_1 < 12; i_1++) {
  90924. _loop_1(i_1);
  90925. }
  90926. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90927. // Create scale cubes
  90928. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90929. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90930. for (var i = 0; i < 2; i++) {
  90931. for (var j = 0; j < 2; j++) {
  90932. var _loop_2 = function () {
  90933. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90934. box.material = coloredMaterial;
  90935. // Dragging logic
  90936. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90937. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90938. _dragBehavior.moveAttached = false;
  90939. box.addBehavior(_dragBehavior);
  90940. _dragBehavior.onDragObservable.add(function (event) {
  90941. _this.onDragObservable.notifyObservers({});
  90942. if (_this.attachedMesh) {
  90943. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  90944. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  90945. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90946. _this.updateBoundingBox();
  90947. // Scale from the position of the opposite corner
  90948. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  90949. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  90950. _this._anchorMesh.addChild(_this.attachedMesh);
  90951. _this._anchorMesh.scaling.addInPlace(deltaScale);
  90952. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  90953. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  90954. }
  90955. _this._anchorMesh.removeChild(_this.attachedMesh);
  90956. }
  90957. });
  90958. // Selection/deselection
  90959. _dragBehavior.onDragStartObservable.add(function () {
  90960. _this.onDragStartObservable.notifyObservers({});
  90961. _this._selectNode(box);
  90962. });
  90963. _dragBehavior.onDragEndObservable.add(function () {
  90964. _this.onDragEndObservable.notifyObservers({});
  90965. _this._selectNode(null);
  90966. });
  90967. this_2._scaleBoxesParent.addChild(box);
  90968. };
  90969. var this_2 = this, _dragBehavior;
  90970. for (var k = 0; k < 2; k++) {
  90971. _loop_2();
  90972. }
  90973. }
  90974. }
  90975. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90976. // Hover color change
  90977. var pointerIds = new Array();
  90978. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90979. if (!pointerIds[pointerInfo.event.pointerId]) {
  90980. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90981. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90982. pointerIds[pointerInfo.event.pointerId] = mesh;
  90983. mesh.material = hoverColoredMaterial;
  90984. }
  90985. });
  90986. }
  90987. else {
  90988. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90989. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90990. delete pointerIds[pointerInfo.event.pointerId];
  90991. }
  90992. }
  90993. });
  90994. // Update bounding box positions
  90995. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90996. // Only update the bouding box if scaling has changed
  90997. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  90998. _this.updateBoundingBox();
  90999. }
  91000. });
  91001. _this.updateBoundingBox();
  91002. return _this;
  91003. }
  91004. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  91005. if (value) {
  91006. // Reset anchor mesh to match attached mesh's scale
  91007. // This is needed to avoid invalid box/sphere position on first drag
  91008. this._anchorMesh.addChild(value);
  91009. this._anchorMesh.removeChild(value);
  91010. this.updateBoundingBox();
  91011. }
  91012. };
  91013. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  91014. this._rotateSpheresParent.getChildMeshes()
  91015. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  91016. m.isVisible = (!selectedMesh || m == selectedMesh);
  91017. });
  91018. };
  91019. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  91020. var _this = this;
  91021. mesh.computeWorldMatrix(true);
  91022. mesh.getChildMeshes().forEach(function (m) {
  91023. _this._recurseComputeWorld(m);
  91024. });
  91025. };
  91026. /**
  91027. * Updates the bounding box information for the Gizmo
  91028. */
  91029. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  91030. this._update();
  91031. if (this.attachedMesh) {
  91032. // Rotate based on axis
  91033. if (!this.attachedMesh.rotationQuaternion) {
  91034. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  91035. }
  91036. if (!this._anchorMesh.rotationQuaternion) {
  91037. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  91038. }
  91039. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  91040. // Store original position and reset mesh to origin before computing the bounding box
  91041. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  91042. this._tmpVector.copyFrom(this.attachedMesh.position);
  91043. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  91044. this.attachedMesh.position.set(0, 0, 0);
  91045. // Update bounding dimensions/positions
  91046. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  91047. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  91048. // Update gizmo to match bounding box scaling and rotation
  91049. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  91050. 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);
  91051. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  91052. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  91053. this._lineBoundingBox.computeWorldMatrix();
  91054. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  91055. // restore position/rotation values
  91056. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  91057. this.attachedMesh.position.copyFrom(this._tmpVector);
  91058. this._recurseComputeWorld(this.attachedMesh);
  91059. }
  91060. // Update rotation sphere locations
  91061. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  91062. for (var i = 0; i < 3; i++) {
  91063. for (var j = 0; j < 2; j++) {
  91064. for (var k = 0; k < 2; k++) {
  91065. var index = ((i * 4) + (j * 2)) + k;
  91066. if (i == 0) {
  91067. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  91068. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91069. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91070. }
  91071. if (i == 1) {
  91072. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  91073. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91074. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91075. }
  91076. if (i == 2) {
  91077. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  91078. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91079. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  91080. }
  91081. if (this.fixedDragMeshScreenSize) {
  91082. this._rootMesh.computeWorldMatrix();
  91083. this._rotateSpheresParent.computeWorldMatrix();
  91084. rotateSpheres[index].computeWorldMatrix();
  91085. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  91086. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  91087. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  91088. }
  91089. else {
  91090. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  91091. }
  91092. }
  91093. }
  91094. }
  91095. // Update scale box locations
  91096. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  91097. for (var i = 0; i < 2; i++) {
  91098. for (var j = 0; j < 2; j++) {
  91099. for (var k = 0; k < 2; k++) {
  91100. var index = ((i * 4) + (j * 2)) + k;
  91101. if (scaleBoxes[index]) {
  91102. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  91103. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91104. if (this.fixedDragMeshScreenSize) {
  91105. this._rootMesh.computeWorldMatrix();
  91106. this._scaleBoxesParent.computeWorldMatrix();
  91107. scaleBoxes[index].computeWorldMatrix();
  91108. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  91109. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  91110. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  91111. }
  91112. else {
  91113. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  91114. }
  91115. }
  91116. }
  91117. }
  91118. }
  91119. if (this.attachedMesh) {
  91120. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  91121. }
  91122. };
  91123. /**
  91124. * Enables rotation on the specified axis and disables rotation on the others
  91125. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  91126. */
  91127. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  91128. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  91129. if (i < 4) {
  91130. m.setEnabled(axis.indexOf("x") != -1);
  91131. }
  91132. else if (i < 8) {
  91133. m.setEnabled(axis.indexOf("y") != -1);
  91134. }
  91135. else {
  91136. m.setEnabled(axis.indexOf("z") != -1);
  91137. }
  91138. });
  91139. };
  91140. /**
  91141. * Disposes of the gizmo
  91142. */
  91143. BoundingBoxGizmo.prototype.dispose = function () {
  91144. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91145. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  91146. this._lineBoundingBox.dispose();
  91147. this._rotateSpheresParent.dispose();
  91148. this._scaleBoxesParent.dispose();
  91149. _super.prototype.dispose.call(this);
  91150. };
  91151. /**
  91152. * 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)
  91153. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  91154. * @returns the bounding box mesh with the passed in mesh as a child
  91155. */
  91156. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  91157. var makeNotPickable = function (root) {
  91158. root.isPickable = false;
  91159. root.getChildMeshes().forEach(function (c) {
  91160. makeNotPickable(c);
  91161. });
  91162. };
  91163. makeNotPickable(mesh);
  91164. // Reset position to get boudning box from origin with no rotation
  91165. if (!mesh.rotationQuaternion) {
  91166. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  91167. }
  91168. var oldPos = mesh.position.clone();
  91169. var oldRot = mesh.rotationQuaternion.clone();
  91170. mesh.rotationQuaternion.set(0, 0, 0, 1);
  91171. mesh.position.set(0, 0, 0);
  91172. // Update bounding dimensions/positions
  91173. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  91174. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  91175. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  91176. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  91177. // Restore original positions
  91178. mesh.addChild(box);
  91179. mesh.rotationQuaternion.copyFrom(oldRot);
  91180. mesh.position.copyFrom(oldPos);
  91181. // Reverse parenting
  91182. mesh.removeChild(box);
  91183. box.addChild(mesh);
  91184. box.visibility = 0;
  91185. return box;
  91186. };
  91187. /**
  91188. * CustomMeshes are not supported by this gizmo
  91189. * @param mesh The mesh to replace the default mesh of the gizmo
  91190. */
  91191. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  91192. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  91193. };
  91194. return BoundingBoxGizmo;
  91195. }(BABYLON.Gizmo));
  91196. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  91197. })(BABYLON || (BABYLON = {}));
  91198. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  91199. var BABYLON;
  91200. (function (BABYLON) {
  91201. /**
  91202. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  91203. */
  91204. var GizmoManager = /** @class */ (function () {
  91205. /**
  91206. * Instatiates a gizmo manager
  91207. * @param scene the scene to overlay the gizmos on top of
  91208. */
  91209. function GizmoManager(scene) {
  91210. var _this = this;
  91211. this.scene = scene;
  91212. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  91213. this._pointerObserver = null;
  91214. this._attachedMesh = null;
  91215. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  91216. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  91217. /**
  91218. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  91219. */
  91220. this.attachableMeshes = null;
  91221. /**
  91222. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  91223. */
  91224. this.usePointerToAttachGizmos = true;
  91225. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  91226. // Instatiate/dispose gizmos based on pointer actions
  91227. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  91228. if (!_this.usePointerToAttachGizmos) {
  91229. return;
  91230. }
  91231. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91232. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  91233. var node = pointerInfo.pickInfo.pickedMesh;
  91234. if (_this.attachableMeshes == null) {
  91235. // Attach to the most parent node
  91236. while (node && node.parent != null) {
  91237. node = node.parent;
  91238. }
  91239. }
  91240. else {
  91241. // Attach to the parent node that is an attachableMesh
  91242. var found = false;
  91243. _this.attachableMeshes.forEach(function (mesh) {
  91244. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  91245. node = mesh;
  91246. found = true;
  91247. }
  91248. });
  91249. if (!found) {
  91250. node = null;
  91251. }
  91252. }
  91253. if (node instanceof BABYLON.AbstractMesh) {
  91254. _this.attachToMesh(node);
  91255. }
  91256. }
  91257. else {
  91258. _this.attachToMesh(null);
  91259. }
  91260. }
  91261. });
  91262. }
  91263. /**
  91264. * Attaches a set of gizmos to the specified mesh
  91265. * @param mesh The mesh the gizmo's should be attached to
  91266. */
  91267. GizmoManager.prototype.attachToMesh = function (mesh) {
  91268. if (this._attachedMesh) {
  91269. this._attachedMesh.removeBehavior(this._dragBehavior);
  91270. }
  91271. this._attachedMesh = mesh;
  91272. for (var key in this.gizmos) {
  91273. var gizmo = (this.gizmos[key]);
  91274. if (gizmo && this._gizmosEnabled[key]) {
  91275. gizmo.attachedMesh = mesh;
  91276. }
  91277. }
  91278. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  91279. this._attachedMesh.addBehavior(this._dragBehavior);
  91280. }
  91281. };
  91282. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  91283. get: function () {
  91284. return this._gizmosEnabled.positionGizmo;
  91285. },
  91286. /**
  91287. * If the position gizmo is enabled
  91288. */
  91289. set: function (value) {
  91290. if (value) {
  91291. this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();
  91292. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91293. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  91294. }
  91295. else if (this.gizmos.positionGizmo) {
  91296. this.gizmos.positionGizmo.attachedMesh = null;
  91297. }
  91298. this._gizmosEnabled.positionGizmo = value;
  91299. },
  91300. enumerable: true,
  91301. configurable: true
  91302. });
  91303. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  91304. get: function () {
  91305. return this._gizmosEnabled.rotationGizmo;
  91306. },
  91307. /**
  91308. * If the rotation gizmo is enabled
  91309. */
  91310. set: function (value) {
  91311. if (value) {
  91312. this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();
  91313. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91314. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  91315. }
  91316. else if (this.gizmos.rotationGizmo) {
  91317. this.gizmos.rotationGizmo.attachedMesh = null;
  91318. }
  91319. this._gizmosEnabled.rotationGizmo = value;
  91320. },
  91321. enumerable: true,
  91322. configurable: true
  91323. });
  91324. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  91325. get: function () {
  91326. return this._gizmosEnabled.scaleGizmo;
  91327. },
  91328. /**
  91329. * If the scale gizmo is enabled
  91330. */
  91331. set: function (value) {
  91332. if (value) {
  91333. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  91334. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  91335. }
  91336. else if (this.gizmos.scaleGizmo) {
  91337. this.gizmos.scaleGizmo.attachedMesh = null;
  91338. }
  91339. this._gizmosEnabled.scaleGizmo = value;
  91340. },
  91341. enumerable: true,
  91342. configurable: true
  91343. });
  91344. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  91345. get: function () {
  91346. return this._gizmosEnabled.boundingBoxGizmo;
  91347. },
  91348. /**
  91349. * If the boundingBox gizmo is enabled
  91350. */
  91351. set: function (value) {
  91352. if (value) {
  91353. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  91354. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  91355. if (this._attachedMesh) {
  91356. this._attachedMesh.removeBehavior(this._dragBehavior);
  91357. this._attachedMesh.addBehavior(this._dragBehavior);
  91358. }
  91359. }
  91360. else if (this.gizmos.boundingBoxGizmo) {
  91361. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  91362. }
  91363. this._gizmosEnabled.boundingBoxGizmo = value;
  91364. },
  91365. enumerable: true,
  91366. configurable: true
  91367. });
  91368. /**
  91369. * Disposes of the gizmo manager
  91370. */
  91371. GizmoManager.prototype.dispose = function () {
  91372. this.scene.onPointerObservable.remove(this._pointerObserver);
  91373. for (var key in this.gizmos) {
  91374. var gizmo = (this.gizmos[key]);
  91375. if (gizmo) {
  91376. gizmo.dispose();
  91377. }
  91378. }
  91379. this._dragBehavior.detach();
  91380. this._gizmoLayer.dispose();
  91381. };
  91382. return GizmoManager;
  91383. }());
  91384. BABYLON.GizmoManager = GizmoManager;
  91385. })(BABYLON || (BABYLON = {}));
  91386. //# sourceMappingURL=babylon.gizmoManager.js.map
  91387. var BABYLON;
  91388. (function (BABYLON) {
  91389. /**
  91390. * Defines a target to use with MorphTargetManager
  91391. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91392. */
  91393. var MorphTarget = /** @class */ (function () {
  91394. /**
  91395. * Creates a new MorphTarget
  91396. * @param name defines the name of the target
  91397. * @param influence defines the influence to use
  91398. */
  91399. function MorphTarget(
  91400. /** defines the name of the target */
  91401. name, influence, scene) {
  91402. if (influence === void 0) { influence = 0; }
  91403. if (scene === void 0) { scene = null; }
  91404. this.name = name;
  91405. /**
  91406. * Gets or sets the list of animations
  91407. */
  91408. this.animations = new Array();
  91409. this._positions = null;
  91410. this._normals = null;
  91411. this._tangents = null;
  91412. /**
  91413. * Observable raised when the influence changes
  91414. */
  91415. this.onInfluenceChanged = new BABYLON.Observable();
  91416. this._animationPropertiesOverride = null;
  91417. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91418. this.influence = influence;
  91419. }
  91420. Object.defineProperty(MorphTarget.prototype, "influence", {
  91421. /**
  91422. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  91423. */
  91424. get: function () {
  91425. return this._influence;
  91426. },
  91427. set: function (influence) {
  91428. if (this._influence === influence) {
  91429. return;
  91430. }
  91431. var previous = this._influence;
  91432. this._influence = influence;
  91433. if (this.onInfluenceChanged.hasObservers) {
  91434. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  91435. }
  91436. },
  91437. enumerable: true,
  91438. configurable: true
  91439. });
  91440. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  91441. /**
  91442. * Gets or sets the animation properties override
  91443. */
  91444. get: function () {
  91445. if (!this._animationPropertiesOverride && this._scene) {
  91446. return this._scene.animationPropertiesOverride;
  91447. }
  91448. return this._animationPropertiesOverride;
  91449. },
  91450. set: function (value) {
  91451. this._animationPropertiesOverride = value;
  91452. },
  91453. enumerable: true,
  91454. configurable: true
  91455. });
  91456. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  91457. /**
  91458. * Gets a boolean defining if the target contains position data
  91459. */
  91460. get: function () {
  91461. return !!this._positions;
  91462. },
  91463. enumerable: true,
  91464. configurable: true
  91465. });
  91466. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  91467. /**
  91468. * Gets a boolean defining if the target contains normal data
  91469. */
  91470. get: function () {
  91471. return !!this._normals;
  91472. },
  91473. enumerable: true,
  91474. configurable: true
  91475. });
  91476. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  91477. /**
  91478. * Gets a boolean defining if the target contains tangent data
  91479. */
  91480. get: function () {
  91481. return !!this._tangents;
  91482. },
  91483. enumerable: true,
  91484. configurable: true
  91485. });
  91486. /**
  91487. * Affects position data to this target
  91488. * @param data defines the position data to use
  91489. */
  91490. MorphTarget.prototype.setPositions = function (data) {
  91491. this._positions = data;
  91492. };
  91493. /**
  91494. * Gets the position data stored in this target
  91495. * @returns a FloatArray containing the position data (or null if not present)
  91496. */
  91497. MorphTarget.prototype.getPositions = function () {
  91498. return this._positions;
  91499. };
  91500. /**
  91501. * Affects normal data to this target
  91502. * @param data defines the normal data to use
  91503. */
  91504. MorphTarget.prototype.setNormals = function (data) {
  91505. this._normals = data;
  91506. };
  91507. /**
  91508. * Gets the normal data stored in this target
  91509. * @returns a FloatArray containing the normal data (or null if not present)
  91510. */
  91511. MorphTarget.prototype.getNormals = function () {
  91512. return this._normals;
  91513. };
  91514. /**
  91515. * Affects tangent data to this target
  91516. * @param data defines the tangent data to use
  91517. */
  91518. MorphTarget.prototype.setTangents = function (data) {
  91519. this._tangents = data;
  91520. };
  91521. /**
  91522. * Gets the tangent data stored in this target
  91523. * @returns a FloatArray containing the tangent data (or null if not present)
  91524. */
  91525. MorphTarget.prototype.getTangents = function () {
  91526. return this._tangents;
  91527. };
  91528. /**
  91529. * Serializes the current target into a Serialization object
  91530. * @returns the serialized object
  91531. */
  91532. MorphTarget.prototype.serialize = function () {
  91533. var serializationObject = {};
  91534. serializationObject.name = this.name;
  91535. serializationObject.influence = this.influence;
  91536. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  91537. if (this.hasNormals) {
  91538. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  91539. }
  91540. if (this.hasTangents) {
  91541. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  91542. }
  91543. // Animations
  91544. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  91545. return serializationObject;
  91546. };
  91547. // Statics
  91548. /**
  91549. * Creates a new target from serialized data
  91550. * @param serializationObject defines the serialized data to use
  91551. * @returns a new MorphTarget
  91552. */
  91553. MorphTarget.Parse = function (serializationObject) {
  91554. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  91555. result.setPositions(serializationObject.positions);
  91556. if (serializationObject.normals) {
  91557. result.setNormals(serializationObject.normals);
  91558. }
  91559. if (serializationObject.tangents) {
  91560. result.setTangents(serializationObject.tangents);
  91561. }
  91562. // Animations
  91563. if (serializationObject.animations) {
  91564. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  91565. var parsedAnimation = serializationObject.animations[animationIndex];
  91566. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  91567. }
  91568. }
  91569. return result;
  91570. };
  91571. /**
  91572. * Creates a MorphTarget from mesh data
  91573. * @param mesh defines the source mesh
  91574. * @param name defines the name to use for the new target
  91575. * @param influence defines the influence to attach to the target
  91576. * @returns a new MorphTarget
  91577. */
  91578. MorphTarget.FromMesh = function (mesh, name, influence) {
  91579. if (!name) {
  91580. name = mesh.name;
  91581. }
  91582. var result = new MorphTarget(name, influence, mesh.getScene());
  91583. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  91584. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91585. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  91586. }
  91587. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  91588. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  91589. }
  91590. return result;
  91591. };
  91592. return MorphTarget;
  91593. }());
  91594. BABYLON.MorphTarget = MorphTarget;
  91595. })(BABYLON || (BABYLON = {}));
  91596. //# sourceMappingURL=babylon.morphTarget.js.map
  91597. var BABYLON;
  91598. (function (BABYLON) {
  91599. /**
  91600. * This class is used to deform meshes using morphing between different targets
  91601. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91602. */
  91603. var MorphTargetManager = /** @class */ (function () {
  91604. /**
  91605. * Creates a new MorphTargetManager
  91606. * @param scene defines the current scene
  91607. */
  91608. function MorphTargetManager(scene) {
  91609. if (scene === void 0) { scene = null; }
  91610. this._targets = new Array();
  91611. this._targetObservable = new Array();
  91612. this._activeTargets = new BABYLON.SmartArray(16);
  91613. this._supportsNormals = false;
  91614. this._supportsTangents = false;
  91615. this._vertexCount = 0;
  91616. this._uniqueId = 0;
  91617. this._tempInfluences = new Array();
  91618. if (!scene) {
  91619. scene = BABYLON.Engine.LastCreatedScene;
  91620. }
  91621. this._scene = scene;
  91622. if (this._scene) {
  91623. this._scene.morphTargetManagers.push(this);
  91624. this._uniqueId = this._scene.getUniqueId();
  91625. }
  91626. }
  91627. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  91628. /**
  91629. * Gets the unique ID of this manager
  91630. */
  91631. get: function () {
  91632. return this._uniqueId;
  91633. },
  91634. enumerable: true,
  91635. configurable: true
  91636. });
  91637. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  91638. /**
  91639. * Gets the number of vertices handled by this manager
  91640. */
  91641. get: function () {
  91642. return this._vertexCount;
  91643. },
  91644. enumerable: true,
  91645. configurable: true
  91646. });
  91647. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  91648. /**
  91649. * Gets a boolean indicating if this manager supports morphing of normals
  91650. */
  91651. get: function () {
  91652. return this._supportsNormals;
  91653. },
  91654. enumerable: true,
  91655. configurable: true
  91656. });
  91657. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  91658. /**
  91659. * Gets a boolean indicating if this manager supports morphing of tangents
  91660. */
  91661. get: function () {
  91662. return this._supportsTangents;
  91663. },
  91664. enumerable: true,
  91665. configurable: true
  91666. });
  91667. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  91668. /**
  91669. * Gets the number of targets stored in this manager
  91670. */
  91671. get: function () {
  91672. return this._targets.length;
  91673. },
  91674. enumerable: true,
  91675. configurable: true
  91676. });
  91677. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  91678. /**
  91679. * Gets the number of influencers (ie. the number of targets with influences > 0)
  91680. */
  91681. get: function () {
  91682. return this._activeTargets.length;
  91683. },
  91684. enumerable: true,
  91685. configurable: true
  91686. });
  91687. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  91688. /**
  91689. * Gets the list of influences (one per target)
  91690. */
  91691. get: function () {
  91692. return this._influences;
  91693. },
  91694. enumerable: true,
  91695. configurable: true
  91696. });
  91697. /**
  91698. * Gets the active target at specified index. An active target is a target with an influence > 0
  91699. * @param index defines the index to check
  91700. * @returns the requested target
  91701. */
  91702. MorphTargetManager.prototype.getActiveTarget = function (index) {
  91703. return this._activeTargets.data[index];
  91704. };
  91705. /**
  91706. * Gets the target at specified index
  91707. * @param index defines the index to check
  91708. * @returns the requested target
  91709. */
  91710. MorphTargetManager.prototype.getTarget = function (index) {
  91711. return this._targets[index];
  91712. };
  91713. /**
  91714. * Add a new target to this manager
  91715. * @param target defines the target to add
  91716. */
  91717. MorphTargetManager.prototype.addTarget = function (target) {
  91718. var _this = this;
  91719. this._targets.push(target);
  91720. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  91721. _this._syncActiveTargets(needUpdate);
  91722. }));
  91723. this._syncActiveTargets(true);
  91724. };
  91725. /**
  91726. * Removes a target from the manager
  91727. * @param target defines the target to remove
  91728. */
  91729. MorphTargetManager.prototype.removeTarget = function (target) {
  91730. var index = this._targets.indexOf(target);
  91731. if (index >= 0) {
  91732. this._targets.splice(index, 1);
  91733. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  91734. this._syncActiveTargets(true);
  91735. }
  91736. };
  91737. /**
  91738. * Serializes the current manager into a Serialization object
  91739. * @returns the serialized object
  91740. */
  91741. MorphTargetManager.prototype.serialize = function () {
  91742. var serializationObject = {};
  91743. serializationObject.id = this.uniqueId;
  91744. serializationObject.targets = [];
  91745. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91746. var target = _a[_i];
  91747. serializationObject.targets.push(target.serialize());
  91748. }
  91749. return serializationObject;
  91750. };
  91751. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  91752. var influenceCount = 0;
  91753. this._activeTargets.reset();
  91754. this._supportsNormals = true;
  91755. this._supportsTangents = true;
  91756. this._vertexCount = 0;
  91757. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91758. var target = _a[_i];
  91759. this._activeTargets.push(target);
  91760. this._tempInfluences[influenceCount++] = target.influence;
  91761. var positions = target.getPositions();
  91762. if (positions) {
  91763. this._supportsNormals = this._supportsNormals && target.hasNormals;
  91764. this._supportsTangents = this._supportsTangents && target.hasTangents;
  91765. var vertexCount = positions.length / 3;
  91766. if (this._vertexCount === 0) {
  91767. this._vertexCount = vertexCount;
  91768. }
  91769. else if (this._vertexCount !== vertexCount) {
  91770. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  91771. return;
  91772. }
  91773. }
  91774. }
  91775. if (!this._influences || this._influences.length !== influenceCount) {
  91776. this._influences = new Float32Array(influenceCount);
  91777. }
  91778. for (var index = 0; index < influenceCount; index++) {
  91779. this._influences[index] = this._tempInfluences[index];
  91780. }
  91781. if (needUpdate) {
  91782. this.synchronize();
  91783. }
  91784. };
  91785. /**
  91786. * Syncrhonize the targets with all the meshes using this morph target manager
  91787. */
  91788. MorphTargetManager.prototype.synchronize = function () {
  91789. if (!this._scene) {
  91790. return;
  91791. }
  91792. // Flag meshes as dirty to resync with the active targets
  91793. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  91794. var mesh = _a[_i];
  91795. if (mesh.morphTargetManager === this) {
  91796. mesh._syncGeometryWithMorphTargetManager();
  91797. }
  91798. }
  91799. };
  91800. // Statics
  91801. /**
  91802. * Creates a new MorphTargetManager from serialized data
  91803. * @param serializationObject defines the serialized data
  91804. * @param scene defines the hosting scene
  91805. * @returns the new MorphTargetManager
  91806. */
  91807. MorphTargetManager.Parse = function (serializationObject, scene) {
  91808. var result = new MorphTargetManager(scene);
  91809. result._uniqueId = serializationObject.id;
  91810. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  91811. var targetData = _a[_i];
  91812. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  91813. }
  91814. return result;
  91815. };
  91816. return MorphTargetManager;
  91817. }());
  91818. BABYLON.MorphTargetManager = MorphTargetManager;
  91819. })(BABYLON || (BABYLON = {}));
  91820. //# sourceMappingURL=babylon.morphTargetManager.js.map
  91821. var BABYLON;
  91822. (function (BABYLON) {
  91823. var Octree = /** @class */ (function () {
  91824. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  91825. if (maxDepth === void 0) { maxDepth = 2; }
  91826. this.maxDepth = maxDepth;
  91827. this.dynamicContent = new Array();
  91828. this._maxBlockCapacity = maxBlockCapacity || 64;
  91829. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  91830. this._creationFunc = creationFunc;
  91831. }
  91832. // Methods
  91833. Octree.prototype.update = function (worldMin, worldMax, entries) {
  91834. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  91835. };
  91836. Octree.prototype.addMesh = function (entry) {
  91837. for (var index = 0; index < this.blocks.length; index++) {
  91838. var block = this.blocks[index];
  91839. block.addEntry(entry);
  91840. }
  91841. };
  91842. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  91843. this._selectionContent.reset();
  91844. for (var index = 0; index < this.blocks.length; index++) {
  91845. var block = this.blocks[index];
  91846. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  91847. }
  91848. if (allowDuplicate) {
  91849. this._selectionContent.concat(this.dynamicContent);
  91850. }
  91851. else {
  91852. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91853. }
  91854. return this._selectionContent;
  91855. };
  91856. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  91857. this._selectionContent.reset();
  91858. for (var index = 0; index < this.blocks.length; index++) {
  91859. var block = this.blocks[index];
  91860. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  91861. }
  91862. if (allowDuplicate) {
  91863. this._selectionContent.concat(this.dynamicContent);
  91864. }
  91865. else {
  91866. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91867. }
  91868. return this._selectionContent;
  91869. };
  91870. Octree.prototype.intersectsRay = function (ray) {
  91871. this._selectionContent.reset();
  91872. for (var index = 0; index < this.blocks.length; index++) {
  91873. var block = this.blocks[index];
  91874. block.intersectsRay(ray, this._selectionContent);
  91875. }
  91876. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91877. return this._selectionContent;
  91878. };
  91879. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91880. target.blocks = new Array();
  91881. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91882. // Segmenting space
  91883. for (var x = 0; x < 2; x++) {
  91884. for (var y = 0; y < 2; y++) {
  91885. for (var z = 0; z < 2; z++) {
  91886. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91887. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91888. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91889. block.addEntries(entries);
  91890. target.blocks.push(block);
  91891. }
  91892. }
  91893. }
  91894. };
  91895. Octree.CreationFuncForMeshes = function (entry, block) {
  91896. var boundingInfo = entry.getBoundingInfo();
  91897. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91898. block.entries.push(entry);
  91899. }
  91900. };
  91901. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91902. var boundingInfo = entry.getBoundingInfo();
  91903. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91904. block.entries.push(entry);
  91905. }
  91906. };
  91907. return Octree;
  91908. }());
  91909. BABYLON.Octree = Octree;
  91910. })(BABYLON || (BABYLON = {}));
  91911. //# sourceMappingURL=babylon.octree.js.map
  91912. var BABYLON;
  91913. (function (BABYLON) {
  91914. var OctreeBlock = /** @class */ (function () {
  91915. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91916. this.entries = new Array();
  91917. this._boundingVectors = new Array();
  91918. this._capacity = capacity;
  91919. this._depth = depth;
  91920. this._maxDepth = maxDepth;
  91921. this._creationFunc = creationFunc;
  91922. this._minPoint = minPoint;
  91923. this._maxPoint = maxPoint;
  91924. this._boundingVectors.push(minPoint.clone());
  91925. this._boundingVectors.push(maxPoint.clone());
  91926. this._boundingVectors.push(minPoint.clone());
  91927. this._boundingVectors[2].x = maxPoint.x;
  91928. this._boundingVectors.push(minPoint.clone());
  91929. this._boundingVectors[3].y = maxPoint.y;
  91930. this._boundingVectors.push(minPoint.clone());
  91931. this._boundingVectors[4].z = maxPoint.z;
  91932. this._boundingVectors.push(maxPoint.clone());
  91933. this._boundingVectors[5].z = minPoint.z;
  91934. this._boundingVectors.push(maxPoint.clone());
  91935. this._boundingVectors[6].x = minPoint.x;
  91936. this._boundingVectors.push(maxPoint.clone());
  91937. this._boundingVectors[7].y = minPoint.y;
  91938. }
  91939. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91940. // Property
  91941. get: function () {
  91942. return this._capacity;
  91943. },
  91944. enumerable: true,
  91945. configurable: true
  91946. });
  91947. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91948. get: function () {
  91949. return this._minPoint;
  91950. },
  91951. enumerable: true,
  91952. configurable: true
  91953. });
  91954. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91955. get: function () {
  91956. return this._maxPoint;
  91957. },
  91958. enumerable: true,
  91959. configurable: true
  91960. });
  91961. // Methods
  91962. OctreeBlock.prototype.addEntry = function (entry) {
  91963. if (this.blocks) {
  91964. for (var index = 0; index < this.blocks.length; index++) {
  91965. var block = this.blocks[index];
  91966. block.addEntry(entry);
  91967. }
  91968. return;
  91969. }
  91970. this._creationFunc(entry, this);
  91971. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91972. this.createInnerBlocks();
  91973. }
  91974. };
  91975. OctreeBlock.prototype.addEntries = function (entries) {
  91976. for (var index = 0; index < entries.length; index++) {
  91977. var mesh = entries[index];
  91978. this.addEntry(mesh);
  91979. }
  91980. };
  91981. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91982. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91983. if (this.blocks) {
  91984. for (var index = 0; index < this.blocks.length; index++) {
  91985. var block = this.blocks[index];
  91986. block.select(frustumPlanes, selection, allowDuplicate);
  91987. }
  91988. return;
  91989. }
  91990. if (allowDuplicate) {
  91991. selection.concat(this.entries);
  91992. }
  91993. else {
  91994. selection.concatWithNoDuplicate(this.entries);
  91995. }
  91996. }
  91997. };
  91998. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91999. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  92000. if (this.blocks) {
  92001. for (var index = 0; index < this.blocks.length; index++) {
  92002. var block = this.blocks[index];
  92003. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  92004. }
  92005. return;
  92006. }
  92007. if (allowDuplicate) {
  92008. selection.concat(this.entries);
  92009. }
  92010. else {
  92011. selection.concatWithNoDuplicate(this.entries);
  92012. }
  92013. }
  92014. };
  92015. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  92016. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  92017. if (this.blocks) {
  92018. for (var index = 0; index < this.blocks.length; index++) {
  92019. var block = this.blocks[index];
  92020. block.intersectsRay(ray, selection);
  92021. }
  92022. return;
  92023. }
  92024. selection.concatWithNoDuplicate(this.entries);
  92025. }
  92026. };
  92027. OctreeBlock.prototype.createInnerBlocks = function () {
  92028. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  92029. };
  92030. return OctreeBlock;
  92031. }());
  92032. BABYLON.OctreeBlock = OctreeBlock;
  92033. })(BABYLON || (BABYLON = {}));
  92034. //# sourceMappingURL=babylon.octreeBlock.js.map
  92035. var BABYLON;
  92036. (function (BABYLON) {
  92037. /**
  92038. * Postprocess used to generate anaglyphic rendering
  92039. */
  92040. var AnaglyphPostProcess = /** @class */ (function (_super) {
  92041. __extends(AnaglyphPostProcess, _super);
  92042. /**
  92043. * Creates a new AnaglyphPostProcess
  92044. * @param name defines postprocess name
  92045. * @param options defines creation options or target ratio scale
  92046. * @param rigCameras defines cameras using this postprocess
  92047. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  92048. * @param engine defines hosting engine
  92049. * @param reusable defines if the postprocess will be reused multiple times per frame
  92050. */
  92051. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  92052. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  92053. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92054. _this.onApplyObservable.add(function (effect) {
  92055. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  92056. });
  92057. return _this;
  92058. }
  92059. return AnaglyphPostProcess;
  92060. }(BABYLON.PostProcess));
  92061. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  92062. })(BABYLON || (BABYLON = {}));
  92063. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  92064. var BABYLON;
  92065. (function (BABYLON) {
  92066. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  92067. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92068. });
  92069. /**
  92070. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  92071. */
  92072. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  92073. __extends(AnaglyphArcRotateCamera, _super);
  92074. /**
  92075. * Creates a new AnaglyphArcRotateCamera
  92076. * @param name defines camera name
  92077. * @param alpha defines alpha angle (in radians)
  92078. * @param beta defines beta angle (in radians)
  92079. * @param radius defines radius
  92080. * @param target defines camera target
  92081. * @param interaxialDistance defines distance between each color axis
  92082. * @param scene defines the hosting scene
  92083. */
  92084. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  92085. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92086. _this.interaxialDistance = interaxialDistance;
  92087. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92088. return _this;
  92089. }
  92090. /**
  92091. * Gets camera class name
  92092. * @returns AnaglyphArcRotateCamera
  92093. */
  92094. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  92095. return "AnaglyphArcRotateCamera";
  92096. };
  92097. return AnaglyphArcRotateCamera;
  92098. }(BABYLON.ArcRotateCamera));
  92099. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  92100. })(BABYLON || (BABYLON = {}));
  92101. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  92102. var BABYLON;
  92103. (function (BABYLON) {
  92104. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  92105. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92106. });
  92107. /**
  92108. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  92109. */
  92110. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  92111. __extends(AnaglyphFreeCamera, _super);
  92112. /**
  92113. * Creates a new AnaglyphFreeCamera
  92114. * @param name defines camera name
  92115. * @param position defines initial position
  92116. * @param interaxialDistance defines distance between each color axis
  92117. * @param scene defines the hosting scene
  92118. */
  92119. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  92120. var _this = _super.call(this, name, position, scene) || this;
  92121. _this.interaxialDistance = interaxialDistance;
  92122. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92123. return _this;
  92124. }
  92125. /**
  92126. * Gets camera class name
  92127. * @returns AnaglyphFreeCamera
  92128. */
  92129. AnaglyphFreeCamera.prototype.getClassName = function () {
  92130. return "AnaglyphFreeCamera";
  92131. };
  92132. return AnaglyphFreeCamera;
  92133. }(BABYLON.FreeCamera));
  92134. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  92135. })(BABYLON || (BABYLON = {}));
  92136. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  92137. var BABYLON;
  92138. (function (BABYLON) {
  92139. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  92140. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92141. });
  92142. /**
  92143. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  92144. */
  92145. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  92146. __extends(AnaglyphGamepadCamera, _super);
  92147. /**
  92148. * Creates a new AnaglyphGamepadCamera
  92149. * @param name defines camera name
  92150. * @param position defines initial position
  92151. * @param interaxialDistance defines distance between each color axis
  92152. * @param scene defines the hosting scene
  92153. */
  92154. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  92155. var _this = _super.call(this, name, position, scene) || this;
  92156. _this.interaxialDistance = interaxialDistance;
  92157. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92158. return _this;
  92159. }
  92160. /**
  92161. * Gets camera class name
  92162. * @returns AnaglyphGamepadCamera
  92163. */
  92164. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92165. return "AnaglyphGamepadCamera";
  92166. };
  92167. return AnaglyphGamepadCamera;
  92168. }(BABYLON.GamepadCamera));
  92169. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92170. })(BABYLON || (BABYLON = {}));
  92171. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  92172. var BABYLON;
  92173. (function (BABYLON) {
  92174. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  92175. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92176. });
  92177. /**
  92178. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92179. */
  92180. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92181. __extends(AnaglyphUniversalCamera, _super);
  92182. /**
  92183. * Creates a new AnaglyphUniversalCamera
  92184. * @param name defines camera name
  92185. * @param position defines initial position
  92186. * @param interaxialDistance defines distance between each color axis
  92187. * @param scene defines the hosting scene
  92188. */
  92189. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92190. var _this = _super.call(this, name, position, scene) || this;
  92191. _this.interaxialDistance = interaxialDistance;
  92192. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92193. return _this;
  92194. }
  92195. /**
  92196. * Gets camera class name
  92197. * @returns AnaglyphUniversalCamera
  92198. */
  92199. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92200. return "AnaglyphUniversalCamera";
  92201. };
  92202. return AnaglyphUniversalCamera;
  92203. }(BABYLON.UniversalCamera));
  92204. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92205. })(BABYLON || (BABYLON = {}));
  92206. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  92207. var BABYLON;
  92208. (function (BABYLON) {
  92209. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  92210. __extends(StereoscopicInterlacePostProcess, _super);
  92211. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  92212. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  92213. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92214. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92215. _this.onSizeChangedObservable.add(function () {
  92216. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92217. });
  92218. _this.onApplyObservable.add(function (effect) {
  92219. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  92220. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  92221. });
  92222. return _this;
  92223. }
  92224. return StereoscopicInterlacePostProcess;
  92225. }(BABYLON.PostProcess));
  92226. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  92227. })(BABYLON || (BABYLON = {}));
  92228. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  92229. var BABYLON;
  92230. (function (BABYLON) {
  92231. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  92232. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92233. });
  92234. /**
  92235. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92236. */
  92237. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92238. __extends(StereoscopicArcRotateCamera, _super);
  92239. /**
  92240. * Creates a new StereoscopicArcRotateCamera
  92241. * @param name defines camera name
  92242. * @param alpha defines alpha angle (in radians)
  92243. * @param beta defines beta angle (in radians)
  92244. * @param radius defines radius
  92245. * @param target defines camera target
  92246. * @param interaxialDistance defines distance between each color axis
  92247. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92248. * @param scene defines the hosting scene
  92249. */
  92250. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92251. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92252. _this.interaxialDistance = interaxialDistance;
  92253. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92254. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92255. return _this;
  92256. }
  92257. /**
  92258. * Gets camera class name
  92259. * @returns StereoscopicArcRotateCamera
  92260. */
  92261. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92262. return "StereoscopicArcRotateCamera";
  92263. };
  92264. return StereoscopicArcRotateCamera;
  92265. }(BABYLON.ArcRotateCamera));
  92266. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92267. })(BABYLON || (BABYLON = {}));
  92268. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  92269. var BABYLON;
  92270. (function (BABYLON) {
  92271. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92272. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92273. });
  92274. /**
  92275. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92276. */
  92277. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92278. __extends(StereoscopicFreeCamera, _super);
  92279. /**
  92280. * Creates a new StereoscopicFreeCamera
  92281. * @param name defines camera name
  92282. * @param position defines initial position
  92283. * @param interaxialDistance defines distance between each color axis
  92284. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92285. * @param scene defines the hosting scene
  92286. */
  92287. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92288. var _this = _super.call(this, name, position, scene) || this;
  92289. _this.interaxialDistance = interaxialDistance;
  92290. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92291. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92292. return _this;
  92293. }
  92294. /**
  92295. * Gets camera class name
  92296. * @returns StereoscopicFreeCamera
  92297. */
  92298. StereoscopicFreeCamera.prototype.getClassName = function () {
  92299. return "StereoscopicFreeCamera";
  92300. };
  92301. return StereoscopicFreeCamera;
  92302. }(BABYLON.FreeCamera));
  92303. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92304. })(BABYLON || (BABYLON = {}));
  92305. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  92306. var BABYLON;
  92307. (function (BABYLON) {
  92308. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  92309. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92310. });
  92311. /**
  92312. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92313. */
  92314. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92315. __extends(StereoscopicGamepadCamera, _super);
  92316. /**
  92317. * Creates a new StereoscopicGamepadCamera
  92318. * @param name defines camera name
  92319. * @param position defines initial position
  92320. * @param interaxialDistance defines distance between each color axis
  92321. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92322. * @param scene defines the hosting scene
  92323. */
  92324. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92325. var _this = _super.call(this, name, position, scene) || this;
  92326. _this.interaxialDistance = interaxialDistance;
  92327. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92328. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92329. return _this;
  92330. }
  92331. /**
  92332. * Gets camera class name
  92333. * @returns StereoscopicGamepadCamera
  92334. */
  92335. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92336. return "StereoscopicGamepadCamera";
  92337. };
  92338. return StereoscopicGamepadCamera;
  92339. }(BABYLON.GamepadCamera));
  92340. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92341. })(BABYLON || (BABYLON = {}));
  92342. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  92343. var BABYLON;
  92344. (function (BABYLON) {
  92345. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92346. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92347. });
  92348. /**
  92349. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92350. */
  92351. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92352. __extends(StereoscopicUniversalCamera, _super);
  92353. /**
  92354. * Creates a new StereoscopicUniversalCamera
  92355. * @param name defines camera name
  92356. * @param position defines initial position
  92357. * @param interaxialDistance defines distance between each color axis
  92358. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92359. * @param scene defines the hosting scene
  92360. */
  92361. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92362. var _this = _super.call(this, name, position, scene) || this;
  92363. _this.interaxialDistance = interaxialDistance;
  92364. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92365. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92366. return _this;
  92367. }
  92368. /**
  92369. * Gets camera class name
  92370. * @returns StereoscopicUniversalCamera
  92371. */
  92372. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92373. return "StereoscopicUniversalCamera";
  92374. };
  92375. return StereoscopicUniversalCamera;
  92376. }(BABYLON.UniversalCamera));
  92377. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92378. })(BABYLON || (BABYLON = {}));
  92379. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  92380. var BABYLON;
  92381. (function (BABYLON) {
  92382. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  92383. __extends(VRDistortionCorrectionPostProcess, _super);
  92384. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  92385. var _this = _super.call(this, name, "vrDistortionCorrection", [
  92386. 'LensCenter',
  92387. 'Scale',
  92388. 'ScaleIn',
  92389. 'HmdWarpParam'
  92390. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  92391. _this._isRightEye = isRightEye;
  92392. _this._distortionFactors = vrMetrics.distortionK;
  92393. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  92394. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  92395. _this.adaptScaleToCurrentViewport = true;
  92396. _this.onSizeChangedObservable.add(function () {
  92397. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  92398. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  92399. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  92400. });
  92401. _this.onApplyObservable.add(function (effect) {
  92402. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  92403. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  92404. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  92405. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  92406. });
  92407. return _this;
  92408. }
  92409. return VRDistortionCorrectionPostProcess;
  92410. }(BABYLON.PostProcess));
  92411. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  92412. })(BABYLON || (BABYLON = {}));
  92413. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  92414. var BABYLON;
  92415. (function (BABYLON) {
  92416. /**
  92417. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  92418. * Screen rotation is taken into account.
  92419. */
  92420. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  92421. function FreeCameraDeviceOrientationInput() {
  92422. var _this = this;
  92423. this._screenOrientationAngle = 0;
  92424. this._screenQuaternion = new BABYLON.Quaternion();
  92425. this._alpha = 0;
  92426. this._beta = 0;
  92427. this._gamma = 0;
  92428. this._orientationChanged = function () {
  92429. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  92430. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  92431. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  92432. };
  92433. this._deviceOrientation = function (evt) {
  92434. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  92435. _this._beta = evt.beta !== null ? evt.beta : 0;
  92436. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  92437. };
  92438. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  92439. this._orientationChanged();
  92440. }
  92441. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  92442. get: function () {
  92443. return this._camera;
  92444. },
  92445. set: function (camera) {
  92446. this._camera = camera;
  92447. if (this._camera != null && !this._camera.rotationQuaternion) {
  92448. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  92449. }
  92450. },
  92451. enumerable: true,
  92452. configurable: true
  92453. });
  92454. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92455. window.addEventListener("orientationchange", this._orientationChanged);
  92456. window.addEventListener("deviceorientation", this._deviceOrientation);
  92457. //In certain cases, the attach control is called AFTER orientation was changed,
  92458. //So this is needed.
  92459. this._orientationChanged();
  92460. };
  92461. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  92462. window.removeEventListener("orientationchange", this._orientationChanged);
  92463. window.removeEventListener("deviceorientation", this._deviceOrientation);
  92464. };
  92465. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  92466. //if no device orientation provided, don't update the rotation.
  92467. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  92468. if (!this._alpha)
  92469. return;
  92470. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  92471. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  92472. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  92473. //Mirror on XY Plane
  92474. this._camera.rotationQuaternion.z *= -1;
  92475. this._camera.rotationQuaternion.w *= -1;
  92476. };
  92477. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  92478. return "FreeCameraDeviceOrientationInput";
  92479. };
  92480. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  92481. return "deviceOrientation";
  92482. };
  92483. return FreeCameraDeviceOrientationInput;
  92484. }());
  92485. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  92486. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  92487. })(BABYLON || (BABYLON = {}));
  92488. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  92489. var BABYLON;
  92490. (function (BABYLON) {
  92491. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  92492. function ArcRotateCameraVRDeviceOrientationInput() {
  92493. this.alphaCorrection = 1;
  92494. this.betaCorrection = 1;
  92495. this.gammaCorrection = 1;
  92496. this._alpha = 0;
  92497. this._gamma = 0;
  92498. this._dirty = false;
  92499. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  92500. }
  92501. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92502. this.camera.attachControl(element, noPreventDefault);
  92503. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  92504. };
  92505. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  92506. if (evt.alpha !== null) {
  92507. this._alpha = +evt.alpha | 0;
  92508. }
  92509. if (evt.gamma !== null) {
  92510. this._gamma = +evt.gamma | 0;
  92511. }
  92512. this._dirty = true;
  92513. };
  92514. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  92515. if (this._dirty) {
  92516. this._dirty = false;
  92517. if (this._gamma < 0) {
  92518. this._gamma = 180 + this._gamma;
  92519. }
  92520. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  92521. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  92522. }
  92523. };
  92524. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  92525. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  92526. };
  92527. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  92528. return "ArcRotateCameraVRDeviceOrientationInput";
  92529. };
  92530. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  92531. return "VRDeviceOrientation";
  92532. };
  92533. return ArcRotateCameraVRDeviceOrientationInput;
  92534. }());
  92535. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  92536. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  92537. })(BABYLON || (BABYLON = {}));
  92538. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  92539. var BABYLON;
  92540. (function (BABYLON) {
  92541. var VRCameraMetrics = /** @class */ (function () {
  92542. function VRCameraMetrics() {
  92543. this.compensateDistortion = true;
  92544. }
  92545. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  92546. get: function () {
  92547. return this.hResolution / (2 * this.vResolution);
  92548. },
  92549. enumerable: true,
  92550. configurable: true
  92551. });
  92552. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  92553. get: function () {
  92554. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  92555. },
  92556. enumerable: true,
  92557. configurable: true
  92558. });
  92559. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  92560. get: function () {
  92561. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92562. var h = (4 * meters) / this.hScreenSize;
  92563. return BABYLON.Matrix.Translation(h, 0, 0);
  92564. },
  92565. enumerable: true,
  92566. configurable: true
  92567. });
  92568. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  92569. get: function () {
  92570. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92571. var h = (4 * meters) / this.hScreenSize;
  92572. return BABYLON.Matrix.Translation(-h, 0, 0);
  92573. },
  92574. enumerable: true,
  92575. configurable: true
  92576. });
  92577. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  92578. get: function () {
  92579. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  92580. },
  92581. enumerable: true,
  92582. configurable: true
  92583. });
  92584. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  92585. get: function () {
  92586. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  92587. },
  92588. enumerable: true,
  92589. configurable: true
  92590. });
  92591. VRCameraMetrics.GetDefault = function () {
  92592. var result = new VRCameraMetrics();
  92593. result.hResolution = 1280;
  92594. result.vResolution = 800;
  92595. result.hScreenSize = 0.149759993;
  92596. result.vScreenSize = 0.0935999975;
  92597. result.vScreenCenter = 0.0467999987;
  92598. result.eyeToScreenDistance = 0.0410000011;
  92599. result.lensSeparationDistance = 0.0635000020;
  92600. result.interpupillaryDistance = 0.0640000030;
  92601. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  92602. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  92603. result.postProcessScaleFactor = 1.714605507808412;
  92604. result.lensCenterOffset = 0.151976421;
  92605. return result;
  92606. };
  92607. return VRCameraMetrics;
  92608. }());
  92609. BABYLON.VRCameraMetrics = VRCameraMetrics;
  92610. })(BABYLON || (BABYLON = {}));
  92611. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  92612. var BABYLON;
  92613. (function (BABYLON) {
  92614. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  92615. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92616. });
  92617. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  92618. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92619. });
  92620. /**
  92621. * This represents a WebVR camera.
  92622. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  92623. * @example http://doc.babylonjs.com/how_to/webvr_camera
  92624. */
  92625. var WebVRFreeCamera = /** @class */ (function (_super) {
  92626. __extends(WebVRFreeCamera, _super);
  92627. /**
  92628. * Instantiates a WebVRFreeCamera.
  92629. * @param name The name of the WebVRFreeCamera
  92630. * @param position The starting anchor position for the camera
  92631. * @param scene The scene the camera belongs to
  92632. * @param webVROptions a set of customizable options for the webVRCamera
  92633. */
  92634. function WebVRFreeCamera(name, position, scene, webVROptions) {
  92635. if (webVROptions === void 0) { webVROptions = {}; }
  92636. var _this = _super.call(this, name, position, scene) || this;
  92637. _this.webVROptions = webVROptions;
  92638. /**
  92639. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  92640. */
  92641. _this._vrDevice = null;
  92642. /**
  92643. * The rawPose of the vrDevice.
  92644. */
  92645. _this.rawPose = null;
  92646. _this._specsVersion = "1.1";
  92647. _this._attached = false;
  92648. _this._descendants = [];
  92649. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  92650. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  92651. /** @hidden */
  92652. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  92653. _this._standingMatrix = null;
  92654. /**
  92655. * Represents device position in babylon space.
  92656. */
  92657. _this.devicePosition = BABYLON.Vector3.Zero();
  92658. /**
  92659. * Represents device rotation in babylon space.
  92660. */
  92661. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  92662. /**
  92663. * The scale of the device to be used when translating from device space to babylon space.
  92664. */
  92665. _this.deviceScaleFactor = 1;
  92666. _this._deviceToWorld = BABYLON.Matrix.Identity();
  92667. _this._worldToDevice = BABYLON.Matrix.Identity();
  92668. /**
  92669. * References to the webVR controllers for the vrDevice.
  92670. */
  92671. _this.controllers = [];
  92672. /**
  92673. * Emits an event when a controller is attached.
  92674. */
  92675. _this.onControllersAttachedObservable = new BABYLON.Observable();
  92676. /**
  92677. * Emits an event when a controller's mesh has been loaded;
  92678. */
  92679. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92680. /**
  92681. * Emits an event when the HMD's pose has been updated.
  92682. */
  92683. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  92684. _this._poseSet = false;
  92685. /**
  92686. * If the rig cameras be used as parent instead of this camera.
  92687. */
  92688. _this.rigParenting = true;
  92689. _this._defaultHeight = undefined;
  92690. _this._workingVector = BABYLON.Vector3.Zero();
  92691. _this._oneVector = BABYLON.Vector3.One();
  92692. _this._workingMatrix = BABYLON.Matrix.Identity();
  92693. _this._cache.position = BABYLON.Vector3.Zero();
  92694. if (webVROptions.defaultHeight) {
  92695. _this._defaultHeight = webVROptions.defaultHeight;
  92696. _this.position.y = _this._defaultHeight;
  92697. }
  92698. _this.minZ = 0.1;
  92699. //legacy support - the compensation boolean was removed.
  92700. if (arguments.length === 5) {
  92701. _this.webVROptions = arguments[4];
  92702. }
  92703. // default webVR options
  92704. if (_this.webVROptions.trackPosition == undefined) {
  92705. _this.webVROptions.trackPosition = true;
  92706. }
  92707. if (_this.webVROptions.controllerMeshes == undefined) {
  92708. _this.webVROptions.controllerMeshes = true;
  92709. }
  92710. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  92711. _this.webVROptions.defaultLightingOnControllers = true;
  92712. }
  92713. _this.rotationQuaternion = new BABYLON.Quaternion();
  92714. if (_this.webVROptions && _this.webVROptions.positionScale) {
  92715. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  92716. }
  92717. //enable VR
  92718. var engine = _this.getEngine();
  92719. _this._onVREnabled = function (success) { if (success) {
  92720. _this.initControllers();
  92721. } };
  92722. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  92723. engine.initWebVR().add(function (event) {
  92724. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  92725. return;
  92726. }
  92727. _this._vrDevice = event.vrDisplay;
  92728. //reset the rig parameters.
  92729. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  92730. if (_this._attached) {
  92731. _this.getEngine().enableVR();
  92732. }
  92733. });
  92734. if (typeof (VRFrameData) !== "undefined")
  92735. _this._frameData = new VRFrameData();
  92736. /**
  92737. * The idea behind the following lines:
  92738. * objects that have the camera as parent should actually have the rig cameras as a parent.
  92739. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  92740. * the second will not show it correctly.
  92741. *
  92742. * To solve this - each object that has the camera as parent will be added to a protected array.
  92743. * When the rig camera renders, it will take this array and set all of those to be its children.
  92744. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  92745. * Amazing!
  92746. */
  92747. scene.onBeforeCameraRenderObservable.add(function (camera) {
  92748. if (camera.parent === _this && _this.rigParenting) {
  92749. _this._descendants = _this.getDescendants(true, function (n) {
  92750. // don't take the cameras or the controllers!
  92751. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  92752. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  92753. return !isController && !isRigCamera;
  92754. });
  92755. _this._descendants.forEach(function (node) {
  92756. node.parent = camera;
  92757. });
  92758. }
  92759. });
  92760. scene.onAfterCameraRenderObservable.add(function (camera) {
  92761. if (camera.parent === _this && _this.rigParenting) {
  92762. _this._descendants.forEach(function (node) {
  92763. node.parent = _this;
  92764. });
  92765. }
  92766. });
  92767. return _this;
  92768. }
  92769. /**
  92770. * Gets the device distance from the ground in meters.
  92771. * @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.
  92772. */
  92773. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  92774. if (this._standingMatrix) {
  92775. // Add standing matrix offset to get real offset from ground in room
  92776. this._standingMatrix.getTranslationToRef(this._workingVector);
  92777. return this._deviceRoomPosition.y + this._workingVector.y;
  92778. }
  92779. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  92780. return this._defaultHeight || 0;
  92781. };
  92782. /**
  92783. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92784. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  92785. */
  92786. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  92787. var _this = this;
  92788. if (callback === void 0) { callback = function (bool) { }; }
  92789. // Use standing matrix if available
  92790. this.getEngine().initWebVRAsync().then(function (result) {
  92791. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  92792. callback(false);
  92793. }
  92794. else {
  92795. _this._standingMatrix = new BABYLON.Matrix();
  92796. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  92797. if (!_this.getScene().useRightHandedSystem) {
  92798. [2, 6, 8, 9, 14].forEach(function (num) {
  92799. if (_this._standingMatrix) {
  92800. _this._standingMatrix.m[num] *= -1;
  92801. }
  92802. });
  92803. }
  92804. callback(true);
  92805. }
  92806. });
  92807. };
  92808. /**
  92809. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92810. * @returns A promise with a boolean set to if the standing matrix is supported.
  92811. */
  92812. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  92813. var _this = this;
  92814. return new Promise(function (res, rej) {
  92815. _this.useStandingMatrix(function (supported) {
  92816. res(supported);
  92817. });
  92818. });
  92819. };
  92820. /**
  92821. * Disposes the camera
  92822. */
  92823. WebVRFreeCamera.prototype.dispose = function () {
  92824. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  92825. _super.prototype.dispose.call(this);
  92826. };
  92827. /**
  92828. * Gets a vrController by name.
  92829. * @param name The name of the controller to retreive
  92830. * @returns the controller matching the name specified or null if not found
  92831. */
  92832. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  92833. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  92834. var gp = _a[_i];
  92835. if (gp.hand === name) {
  92836. return gp;
  92837. }
  92838. }
  92839. return null;
  92840. };
  92841. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  92842. /**
  92843. * The controller corrisponding to the users left hand.
  92844. */
  92845. get: function () {
  92846. if (!this._leftController) {
  92847. this._leftController = this.getControllerByName("left");
  92848. }
  92849. return this._leftController;
  92850. },
  92851. enumerable: true,
  92852. configurable: true
  92853. });
  92854. ;
  92855. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  92856. /**
  92857. * The controller corrisponding to the users right hand.
  92858. */
  92859. get: function () {
  92860. if (!this._rightController) {
  92861. this._rightController = this.getControllerByName("right");
  92862. }
  92863. return this._rightController;
  92864. },
  92865. enumerable: true,
  92866. configurable: true
  92867. });
  92868. ;
  92869. /**
  92870. * Casts a ray forward from the vrCamera's gaze.
  92871. * @param length Length of the ray (default: 100)
  92872. * @returns the ray corrisponding to the gaze
  92873. */
  92874. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  92875. if (length === void 0) { length = 100; }
  92876. if (this.leftCamera) {
  92877. // Use left eye to avoid computation to compute center on every call
  92878. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  92879. }
  92880. else {
  92881. return _super.prototype.getForwardRay.call(this, length);
  92882. }
  92883. };
  92884. /**
  92885. * Updates the camera based on device's frame data
  92886. */
  92887. WebVRFreeCamera.prototype._checkInputs = function () {
  92888. if (this._vrDevice && this._vrDevice.isPresenting) {
  92889. this._vrDevice.getFrameData(this._frameData);
  92890. this.updateFromDevice(this._frameData.pose);
  92891. }
  92892. _super.prototype._checkInputs.call(this);
  92893. };
  92894. /**
  92895. * Updates the poseControlled values based on the input device pose.
  92896. * @param poseData Pose coming from the device
  92897. */
  92898. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  92899. if (poseData && poseData.orientation) {
  92900. this.rawPose = poseData;
  92901. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  92902. if (this.getScene().useRightHandedSystem) {
  92903. this._deviceRoomRotationQuaternion.z *= -1;
  92904. this._deviceRoomRotationQuaternion.w *= -1;
  92905. }
  92906. if (this.webVROptions.trackPosition && this.rawPose.position) {
  92907. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  92908. if (this.getScene().useRightHandedSystem) {
  92909. this._deviceRoomPosition.z *= -1;
  92910. }
  92911. }
  92912. this._poseSet = true;
  92913. }
  92914. };
  92915. /**
  92916. * WebVR's attach control will start broadcasting frames to the device.
  92917. * Note that in certain browsers (chrome for example) this function must be called
  92918. * within a user-interaction callback. Example:
  92919. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  92920. *
  92921. * @param element html element to attach the vrDevice to
  92922. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  92923. */
  92924. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  92925. _super.prototype.attachControl.call(this, element, noPreventDefault);
  92926. this._attached = true;
  92927. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  92928. if (this._vrDevice) {
  92929. this.getEngine().enableVR();
  92930. }
  92931. };
  92932. /**
  92933. * Detaches the camera from the html element and disables VR
  92934. *
  92935. * @param element html element to detach from
  92936. */
  92937. WebVRFreeCamera.prototype.detachControl = function (element) {
  92938. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  92939. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  92940. _super.prototype.detachControl.call(this, element);
  92941. this._attached = false;
  92942. this.getEngine().disableVR();
  92943. };
  92944. /**
  92945. * @returns the name of this class
  92946. */
  92947. WebVRFreeCamera.prototype.getClassName = function () {
  92948. return "WebVRFreeCamera";
  92949. };
  92950. /**
  92951. * Calls resetPose on the vrDisplay
  92952. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  92953. */
  92954. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  92955. //uses the vrDisplay's "resetPose()".
  92956. //pitch and roll won't be affected.
  92957. this._vrDevice.resetPose();
  92958. };
  92959. /**
  92960. * Updates the rig cameras (left and right eye)
  92961. */
  92962. WebVRFreeCamera.prototype._updateRigCameras = function () {
  92963. var camLeft = this._rigCameras[0];
  92964. var camRight = this._rigCameras[1];
  92965. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92966. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92967. camLeft.position.copyFrom(this._deviceRoomPosition);
  92968. camRight.position.copyFrom(this._deviceRoomPosition);
  92969. };
  92970. /**
  92971. * Updates the cached values of the camera
  92972. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  92973. */
  92974. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  92975. var _this = this;
  92976. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  92977. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  92978. if (!this.updateCacheCalled) {
  92979. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  92980. this.updateCacheCalled = true;
  92981. this.update();
  92982. }
  92983. // Set working vector to the device position in room space rotated by the new rotation
  92984. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  92985. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  92986. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  92987. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  92988. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  92989. // Add translation from anchor position
  92990. this._deviceToWorld.getTranslationToRef(this._workingVector);
  92991. this._workingVector.addInPlace(this.position);
  92992. this._workingVector.subtractInPlace(this._cache.position);
  92993. this._deviceToWorld.setTranslation(this._workingVector);
  92994. // Set an inverted matrix to be used when updating the camera
  92995. this._deviceToWorld.invertToRef(this._worldToDevice);
  92996. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  92997. this.controllers.forEach(function (controller) {
  92998. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  92999. controller.update();
  93000. });
  93001. }
  93002. if (!ignoreParentClass) {
  93003. _super.prototype._updateCache.call(this);
  93004. }
  93005. this.updateCacheCalled = false;
  93006. };
  93007. /**
  93008. * Updates the current device position and rotation in the babylon world
  93009. */
  93010. WebVRFreeCamera.prototype.update = function () {
  93011. // Get current device position in babylon world
  93012. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  93013. // Get current device rotation in babylon world
  93014. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  93015. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  93016. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  93017. if (this._poseSet) {
  93018. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  93019. }
  93020. _super.prototype.update.call(this);
  93021. };
  93022. /**
  93023. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  93024. * @returns an identity matrix
  93025. */
  93026. WebVRFreeCamera.prototype._getViewMatrix = function () {
  93027. return BABYLON.Matrix.Identity();
  93028. };
  93029. /**
  93030. * This function is called by the two RIG cameras.
  93031. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  93032. */
  93033. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  93034. var _this = this;
  93035. // Update the parent camera prior to using a child camera to avoid desynchronization
  93036. var parentCamera = this._cameraRigParams["parentCamera"];
  93037. parentCamera._updateCache();
  93038. //WebVR 1.1
  93039. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  93040. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  93041. if (!this.getScene().useRightHandedSystem) {
  93042. [2, 6, 8, 9, 14].forEach(function (num) {
  93043. _this._webvrViewMatrix.m[num] *= -1;
  93044. });
  93045. }
  93046. // update the camera rotation matrix
  93047. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  93048. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  93049. // Computing target and final matrix
  93050. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  93051. // should the view matrix be updated with scale and position offset?
  93052. if (parentCamera.deviceScaleFactor !== 1) {
  93053. this._webvrViewMatrix.invert();
  93054. // scale the position, if set
  93055. if (parentCamera.deviceScaleFactor) {
  93056. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  93057. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  93058. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  93059. }
  93060. this._webvrViewMatrix.invert();
  93061. }
  93062. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  93063. // Compute global position
  93064. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  93065. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  93066. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  93067. this._workingMatrix.getTranslationToRef(this._globalPosition);
  93068. this._markSyncedWithParent();
  93069. return this._webvrViewMatrix;
  93070. };
  93071. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  93072. var _this = this;
  93073. var parentCamera = this.parent;
  93074. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  93075. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  93076. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  93077. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  93078. //babylon compatible matrix
  93079. if (!this.getScene().useRightHandedSystem) {
  93080. [8, 9, 10, 11].forEach(function (num) {
  93081. _this._projectionMatrix.m[num] *= -1;
  93082. });
  93083. }
  93084. return this._projectionMatrix;
  93085. };
  93086. /**
  93087. * Initializes the controllers and their meshes
  93088. */
  93089. WebVRFreeCamera.prototype.initControllers = function () {
  93090. var _this = this;
  93091. this.controllers = [];
  93092. var manager = this.getScene().gamepadManager;
  93093. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  93094. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  93095. var webVrController = gamepad;
  93096. if (webVrController.defaultModel) {
  93097. webVrController.defaultModel.setEnabled(false);
  93098. }
  93099. if (webVrController.hand === "right") {
  93100. _this._rightController = null;
  93101. }
  93102. if (webVrController.hand === "left") {
  93103. _this._leftController = null;
  93104. }
  93105. var controllerIndex = _this.controllers.indexOf(webVrController);
  93106. if (controllerIndex !== -1) {
  93107. _this.controllers.splice(controllerIndex, 1);
  93108. }
  93109. }
  93110. });
  93111. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  93112. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  93113. var webVrController_1 = gamepad;
  93114. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  93115. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  93116. if (_this.webVROptions.controllerMeshes) {
  93117. if (webVrController_1.defaultModel) {
  93118. webVrController_1.defaultModel.setEnabled(true);
  93119. }
  93120. else {
  93121. // Load the meshes
  93122. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  93123. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  93124. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  93125. if (_this.webVROptions.defaultLightingOnControllers) {
  93126. if (!_this._lightOnControllers) {
  93127. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  93128. }
  93129. var activateLightOnSubMeshes_1 = function (mesh, light) {
  93130. var children = mesh.getChildren();
  93131. if (children.length !== 0) {
  93132. children.forEach(function (mesh) {
  93133. light.includedOnlyMeshes.push(mesh);
  93134. activateLightOnSubMeshes_1(mesh, light);
  93135. });
  93136. }
  93137. };
  93138. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  93139. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  93140. }
  93141. });
  93142. }
  93143. }
  93144. webVrController_1.attachToPoseControlledCamera(_this);
  93145. // since this is async - sanity check. Is the controller already stored?
  93146. if (_this.controllers.indexOf(webVrController_1) === -1) {
  93147. //add to the controllers array
  93148. _this.controllers.push(webVrController_1);
  93149. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  93150. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  93151. // So we're overriding setting left & right manually to be sure
  93152. var firstViveWandDetected = false;
  93153. for (var i = 0; i < _this.controllers.length; i++) {
  93154. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93155. if (!firstViveWandDetected) {
  93156. firstViveWandDetected = true;
  93157. _this.controllers[i].hand = "left";
  93158. }
  93159. else {
  93160. _this.controllers[i].hand = "right";
  93161. }
  93162. }
  93163. }
  93164. //did we find enough controllers? Great! let the developer know.
  93165. if (_this.controllers.length >= 2) {
  93166. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  93167. }
  93168. }
  93169. }
  93170. });
  93171. };
  93172. return WebVRFreeCamera;
  93173. }(BABYLON.FreeCamera));
  93174. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  93175. })(BABYLON || (BABYLON = {}));
  93176. //# sourceMappingURL=babylon.webVRCamera.js.map
  93177. var BABYLON;
  93178. (function (BABYLON) {
  93179. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  93180. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  93181. });
  93182. // We're mainly based on the logic defined into the FreeCamera code
  93183. /**
  93184. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  93185. * being tilted forward or back and left or right.
  93186. */
  93187. var DeviceOrientationCamera = /** @class */ (function (_super) {
  93188. __extends(DeviceOrientationCamera, _super);
  93189. /**
  93190. * Creates a new device orientation camera
  93191. * @param name The name of the camera
  93192. * @param position The start position camera
  93193. * @param scene The scene the camera belongs to
  93194. */
  93195. function DeviceOrientationCamera(name, position, scene) {
  93196. var _this = _super.call(this, name, position, scene) || this;
  93197. _this._quaternionCache = new BABYLON.Quaternion();
  93198. _this.inputs.addDeviceOrientation();
  93199. return _this;
  93200. }
  93201. /**
  93202. * Gets the current instance class name ("DeviceOrientationCamera").
  93203. * This helps avoiding instanceof at run time.
  93204. * @returns the class name
  93205. */
  93206. DeviceOrientationCamera.prototype.getClassName = function () {
  93207. return "DeviceOrientationCamera";
  93208. };
  93209. /**
  93210. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  93211. */
  93212. DeviceOrientationCamera.prototype._checkInputs = function () {
  93213. _super.prototype._checkInputs.call(this);
  93214. this._quaternionCache.copyFrom(this.rotationQuaternion);
  93215. if (this._initialQuaternion) {
  93216. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93217. }
  93218. };
  93219. /**
  93220. * Reset the camera to its default orientation on the specified axis only.
  93221. * @param axis The axis to reset
  93222. */
  93223. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  93224. var _this = this;
  93225. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  93226. //can only work if this camera has a rotation quaternion already.
  93227. if (!this.rotationQuaternion)
  93228. return;
  93229. if (!this._initialQuaternion) {
  93230. this._initialQuaternion = new BABYLON.Quaternion();
  93231. }
  93232. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  93233. ['x', 'y', 'z'].forEach(function (axisName) {
  93234. if (!axis[axisName]) {
  93235. _this._initialQuaternion[axisName] = 0;
  93236. }
  93237. else {
  93238. _this._initialQuaternion[axisName] *= -1;
  93239. }
  93240. });
  93241. this._initialQuaternion.normalize();
  93242. //force rotation update
  93243. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93244. };
  93245. return DeviceOrientationCamera;
  93246. }(BABYLON.FreeCamera));
  93247. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  93248. })(BABYLON || (BABYLON = {}));
  93249. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  93250. var BABYLON;
  93251. (function (BABYLON) {
  93252. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93253. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93254. });
  93255. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  93256. __extends(VRDeviceOrientationFreeCamera, _super);
  93257. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93258. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93259. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93260. var _this = _super.call(this, name, position, scene) || this;
  93261. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93262. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93263. return _this;
  93264. }
  93265. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  93266. return "VRDeviceOrientationFreeCamera";
  93267. };
  93268. return VRDeviceOrientationFreeCamera;
  93269. }(BABYLON.DeviceOrientationCamera));
  93270. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  93271. })(BABYLON || (BABYLON = {}));
  93272. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  93273. var BABYLON;
  93274. (function (BABYLON) {
  93275. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93276. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  93277. });
  93278. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  93279. __extends(VRDeviceOrientationArcRotateCamera, _super);
  93280. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  93281. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93282. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93283. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93284. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93285. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93286. _this.inputs.addVRDeviceOrientation();
  93287. return _this;
  93288. }
  93289. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  93290. return "VRDeviceOrientationArcRotateCamera";
  93291. };
  93292. return VRDeviceOrientationArcRotateCamera;
  93293. }(BABYLON.ArcRotateCamera));
  93294. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  93295. })(BABYLON || (BABYLON = {}));
  93296. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  93297. var BABYLON;
  93298. (function (BABYLON) {
  93299. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  93300. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  93301. });
  93302. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  93303. __extends(VRDeviceOrientationGamepadCamera, _super);
  93304. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93305. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93306. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93307. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  93308. _this.inputs.addGamepad();
  93309. return _this;
  93310. }
  93311. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  93312. return "VRDeviceOrientationGamepadCamera";
  93313. };
  93314. return VRDeviceOrientationGamepadCamera;
  93315. }(BABYLON.VRDeviceOrientationFreeCamera));
  93316. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  93317. })(BABYLON || (BABYLON = {}));
  93318. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  93319. var BABYLON;
  93320. (function (BABYLON) {
  93321. var VRExperienceHelperGazer = /** @class */ (function () {
  93322. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  93323. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  93324. this.scene = scene;
  93325. this._pointerDownOnMeshAsked = false;
  93326. this._isActionableMesh = false;
  93327. this._teleportationRequestInitiated = false;
  93328. this._teleportationBackRequestInitiated = false;
  93329. this._rotationRightAsked = false;
  93330. this._rotationLeftAsked = false;
  93331. this._dpadPressed = true;
  93332. this._activePointer = false;
  93333. this._id = VRExperienceHelperGazer._idCounter++;
  93334. // Gaze tracker
  93335. if (!gazeTrackerToClone) {
  93336. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  93337. this._gazeTracker.bakeCurrentTransformIntoVertices();
  93338. this._gazeTracker.isPickable = false;
  93339. this._gazeTracker.isVisible = false;
  93340. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  93341. targetMat.specularColor = BABYLON.Color3.Black();
  93342. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93343. targetMat.backFaceCulling = false;
  93344. this._gazeTracker.material = targetMat;
  93345. }
  93346. else {
  93347. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  93348. }
  93349. }
  93350. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  93351. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  93352. };
  93353. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  93354. this._pointerDownOnMeshAsked = true;
  93355. if (this._currentHit) {
  93356. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  93357. }
  93358. };
  93359. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  93360. if (this._currentHit) {
  93361. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  93362. }
  93363. this._pointerDownOnMeshAsked = false;
  93364. };
  93365. VRExperienceHelperGazer.prototype._activatePointer = function () {
  93366. this._activePointer = true;
  93367. };
  93368. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  93369. this._activePointer = false;
  93370. };
  93371. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  93372. if (distance === void 0) { distance = 100; }
  93373. };
  93374. VRExperienceHelperGazer.prototype.dispose = function () {
  93375. this._interactionsEnabled = false;
  93376. this._teleportationEnabled = false;
  93377. if (this._gazeTracker) {
  93378. this._gazeTracker.dispose();
  93379. }
  93380. };
  93381. VRExperienceHelperGazer._idCounter = 0;
  93382. return VRExperienceHelperGazer;
  93383. }());
  93384. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  93385. __extends(VRExperienceHelperControllerGazer, _super);
  93386. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  93387. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  93388. _this.webVRController = webVRController;
  93389. // Laser pointer
  93390. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  93391. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  93392. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93393. laserPointerMaterial.alpha = 0.6;
  93394. _this._laserPointer.material = laserPointerMaterial;
  93395. _this._laserPointer.rotation.x = Math.PI / 2;
  93396. _this._laserPointer.position.z = -0.5;
  93397. _this._laserPointer.isVisible = false;
  93398. _this._laserPointer.isPickable = false;
  93399. if (!webVRController.mesh) {
  93400. // Create an empty mesh that is used prior to loading the high quality model
  93401. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  93402. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  93403. preloadPointerPose.rotation.x = -0.7;
  93404. preloadMesh.addChild(preloadPointerPose);
  93405. webVRController.attachToMesh(preloadMesh);
  93406. }
  93407. _this._setLaserPointerParent(webVRController.mesh);
  93408. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  93409. _this._setLaserPointerParent(mesh);
  93410. });
  93411. return _this;
  93412. }
  93413. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  93414. return this.webVRController.getForwardRay(length);
  93415. };
  93416. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  93417. _super.prototype._activatePointer.call(this);
  93418. this._laserPointer.isVisible = true;
  93419. };
  93420. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  93421. _super.prototype._deactivatePointer.call(this);
  93422. this._laserPointer.isVisible = false;
  93423. };
  93424. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  93425. this._laserPointer.material.emissiveColor = color;
  93426. };
  93427. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  93428. var makeNotPick = function (root) {
  93429. root.isPickable = false;
  93430. root.getChildMeshes().forEach(function (c) {
  93431. makeNotPick(c);
  93432. });
  93433. };
  93434. makeNotPick(mesh);
  93435. var childMeshes = mesh.getChildMeshes();
  93436. this.webVRController._pointingPoseNode = null;
  93437. for (var i = 0; i < childMeshes.length; i++) {
  93438. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  93439. mesh = childMeshes[i];
  93440. this.webVRController._pointingPoseNode = mesh;
  93441. break;
  93442. }
  93443. }
  93444. this._laserPointer.parent = mesh;
  93445. };
  93446. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  93447. if (distance === void 0) { distance = 100; }
  93448. this._laserPointer.scaling.y = distance;
  93449. this._laserPointer.position.z = -distance / 2;
  93450. };
  93451. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  93452. _super.prototype.dispose.call(this);
  93453. this._laserPointer.dispose();
  93454. if (this._meshAttachedObserver) {
  93455. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  93456. }
  93457. };
  93458. return VRExperienceHelperControllerGazer;
  93459. }(VRExperienceHelperGazer));
  93460. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  93461. __extends(VRExperienceHelperCameraGazer, _super);
  93462. function VRExperienceHelperCameraGazer(getCamera, scene) {
  93463. var _this = _super.call(this, scene) || this;
  93464. _this.getCamera = getCamera;
  93465. return _this;
  93466. }
  93467. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  93468. var camera = this.getCamera();
  93469. if (camera) {
  93470. return camera.getForwardRay(length);
  93471. }
  93472. else {
  93473. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  93474. }
  93475. };
  93476. return VRExperienceHelperCameraGazer;
  93477. }(VRExperienceHelperGazer));
  93478. /**
  93479. * Helps to quickly add VR support to an existing scene.
  93480. * See http://doc.babylonjs.com/how_to/webvr_helper
  93481. */
  93482. var VRExperienceHelper = /** @class */ (function () {
  93483. /**
  93484. * Instantiates a VRExperienceHelper.
  93485. * Helps to quickly add VR support to an existing scene.
  93486. * @param scene The scene the VRExperienceHelper belongs to.
  93487. * @param webVROptions Options to modify the vr experience helper's behavior.
  93488. */
  93489. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  93490. if (webVROptions === void 0) { webVROptions = {}; }
  93491. var _this = this;
  93492. this.webVROptions = webVROptions;
  93493. // Can the system support WebVR, even if a headset isn't plugged in?
  93494. this._webVRsupported = false;
  93495. // If WebVR is supported, is a headset plugged in and are we ready to present?
  93496. this._webVRready = false;
  93497. // Are we waiting for the requestPresent callback to complete?
  93498. this._webVRrequesting = false;
  93499. // Are we presenting to the headset right now?
  93500. this._webVRpresenting = false;
  93501. // Are we presenting in the fullscreen fallback?
  93502. this._fullscreenVRpresenting = false;
  93503. /**
  93504. * Observable raised when entering VR.
  93505. */
  93506. this.onEnteringVRObservable = new BABYLON.Observable();
  93507. /**
  93508. * Observable raised when exiting VR.
  93509. */
  93510. this.onExitingVRObservable = new BABYLON.Observable();
  93511. /**
  93512. * Observable raised when controller mesh is loaded.
  93513. */
  93514. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  93515. this._useCustomVRButton = false;
  93516. this._teleportationRequested = false;
  93517. this._teleportActive = false;
  93518. this._floorMeshesCollection = [];
  93519. this._rotationAllowed = true;
  93520. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  93521. this._isDefaultTeleportationTarget = true;
  93522. this._teleportationFillColor = "#444444";
  93523. this._teleportationBorderColor = "#FFFFFF";
  93524. this._rotationAngle = 0;
  93525. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  93526. this._padSensibilityUp = 0.65;
  93527. this._padSensibilityDown = 0.35;
  93528. this.leftController = null;
  93529. this.rightController = null;
  93530. /**
  93531. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  93532. */
  93533. this.onNewMeshSelected = new BABYLON.Observable();
  93534. /**
  93535. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  93536. */
  93537. this.onNewMeshPicked = new BABYLON.Observable();
  93538. /**
  93539. * Observable raised before camera teleportation
  93540. */
  93541. this.onBeforeCameraTeleport = new BABYLON.Observable();
  93542. /**
  93543. * Observable raised after camera teleportation
  93544. */
  93545. this.onAfterCameraTeleport = new BABYLON.Observable();
  93546. /**
  93547. * Observable raised when current selected mesh gets unselected
  93548. */
  93549. this.onSelectedMeshUnselected = new BABYLON.Observable();
  93550. /**
  93551. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  93552. */
  93553. this.teleportationEnabled = true;
  93554. this._teleportationInitialized = false;
  93555. this._interactionsEnabled = false;
  93556. this._interactionsRequested = false;
  93557. this._displayGaze = true;
  93558. this._displayLaserPointer = true;
  93559. this._onResize = function () {
  93560. _this.moveButtonToBottomRight();
  93561. if (_this._fullscreenVRpresenting && _this._webVRready) {
  93562. _this.exitVR();
  93563. }
  93564. };
  93565. this._onFullscreenChange = function () {
  93566. if (document.fullscreen !== undefined) {
  93567. _this._fullscreenVRpresenting = document.fullscreen;
  93568. }
  93569. else if (document.mozFullScreen !== undefined) {
  93570. _this._fullscreenVRpresenting = document.mozFullScreen;
  93571. }
  93572. else if (document.webkitIsFullScreen !== undefined) {
  93573. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  93574. }
  93575. else if (document.msIsFullScreen !== undefined) {
  93576. _this._fullscreenVRpresenting = document.msIsFullScreen;
  93577. }
  93578. else if (document.msFullscreenElement !== undefined) {
  93579. _this._fullscreenVRpresenting = document.msFullscreenElement;
  93580. }
  93581. if (!_this._fullscreenVRpresenting && _this._canvas) {
  93582. _this.exitVR();
  93583. if (!_this._useCustomVRButton) {
  93584. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  93585. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  93586. }
  93587. }
  93588. };
  93589. this.beforeRender = function () {
  93590. if (_this.leftController && _this.leftController._activePointer) {
  93591. _this._castRayAndSelectObject(_this.leftController);
  93592. }
  93593. if (_this.rightController && _this.rightController._activePointer) {
  93594. _this._castRayAndSelectObject(_this.rightController);
  93595. }
  93596. if (_this._noControllerIsActive) {
  93597. _this._castRayAndSelectObject(_this._cameraGazer);
  93598. }
  93599. else {
  93600. _this._cameraGazer._gazeTracker.isVisible = false;
  93601. }
  93602. };
  93603. this._onNewGamepadConnected = function (gamepad) {
  93604. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  93605. if (gamepad.leftStick) {
  93606. gamepad.onleftstickchanged(function (stickValues) {
  93607. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  93608. // Listening to classic/xbox gamepad only if no VR controller is active
  93609. if ((!_this.leftController && !_this.rightController) ||
  93610. ((_this.leftController && !_this.leftController._activePointer) &&
  93611. (_this.rightController && !_this.rightController._activePointer))) {
  93612. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  93613. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  93614. }
  93615. }
  93616. });
  93617. }
  93618. if (gamepad.rightStick) {
  93619. gamepad.onrightstickchanged(function (stickValues) {
  93620. if (_this._teleportationInitialized) {
  93621. _this._checkRotate(stickValues, _this._cameraGazer);
  93622. }
  93623. });
  93624. }
  93625. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  93626. gamepad.onbuttondown(function (buttonPressed) {
  93627. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93628. _this._cameraGazer._selectionPointerDown();
  93629. }
  93630. });
  93631. gamepad.onbuttonup(function (buttonPressed) {
  93632. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93633. _this._cameraGazer._selectionPointerUp();
  93634. }
  93635. });
  93636. }
  93637. }
  93638. else {
  93639. var webVRController = gamepad;
  93640. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  93641. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  93642. _this.rightController = controller;
  93643. }
  93644. else {
  93645. _this.leftController = controller;
  93646. }
  93647. _this._tryEnableInteractionOnController(controller);
  93648. }
  93649. };
  93650. // 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
  93651. this._tryEnableInteractionOnController = function (controller) {
  93652. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  93653. _this._enableInteractionOnController(controller);
  93654. }
  93655. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  93656. _this._enableTeleportationOnController(controller);
  93657. }
  93658. };
  93659. this._onNewGamepadDisconnected = function (gamepad) {
  93660. if (gamepad instanceof BABYLON.WebVRController) {
  93661. if (gamepad.hand === "left" && _this.leftController != null) {
  93662. _this.leftController.dispose();
  93663. _this.leftController = null;
  93664. }
  93665. if (gamepad.hand === "right" && _this.rightController != null) {
  93666. _this.rightController.dispose();
  93667. _this.rightController = null;
  93668. }
  93669. }
  93670. };
  93671. this._workingVector = BABYLON.Vector3.Zero();
  93672. this._workingQuaternion = BABYLON.Quaternion.Identity();
  93673. this._workingMatrix = BABYLON.Matrix.Identity();
  93674. this._scene = scene;
  93675. this._canvas = scene.getEngine().getRenderingCanvas();
  93676. // Parse options
  93677. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  93678. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  93679. }
  93680. if (webVROptions.createDeviceOrientationCamera === undefined) {
  93681. webVROptions.createDeviceOrientationCamera = true;
  93682. }
  93683. if (webVROptions.laserToggle === undefined) {
  93684. webVROptions.laserToggle = true;
  93685. }
  93686. if (webVROptions.defaultHeight === undefined) {
  93687. webVROptions.defaultHeight = 1.7;
  93688. }
  93689. if (webVROptions.useCustomVRButton) {
  93690. this._useCustomVRButton = true;
  93691. if (webVROptions.customVRButton) {
  93692. this._btnVR = webVROptions.customVRButton;
  93693. }
  93694. }
  93695. if (webVROptions.rayLength) {
  93696. this._rayLength = webVROptions.rayLength;
  93697. }
  93698. this._defaultHeight = webVROptions.defaultHeight;
  93699. if (webVROptions.positionScale) {
  93700. this._rayLength *= webVROptions.positionScale;
  93701. this._defaultHeight *= webVROptions.positionScale;
  93702. }
  93703. // Set position
  93704. if (this._scene.activeCamera) {
  93705. this._position = this._scene.activeCamera.position.clone();
  93706. }
  93707. else {
  93708. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  93709. }
  93710. // Set non-vr camera
  93711. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  93712. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  93713. // Copy data from existing camera
  93714. if (this._scene.activeCamera) {
  93715. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93716. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  93717. // Set rotation from previous camera
  93718. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  93719. var targetCamera = this._scene.activeCamera;
  93720. if (targetCamera.rotationQuaternion) {
  93721. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  93722. }
  93723. else {
  93724. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  93725. }
  93726. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  93727. }
  93728. }
  93729. this._scene.activeCamera = this._deviceOrientationCamera;
  93730. if (this._canvas) {
  93731. this._scene.activeCamera.attachControl(this._canvas);
  93732. }
  93733. }
  93734. else {
  93735. this._existingCamera = this._scene.activeCamera;
  93736. }
  93737. // Create VR cameras
  93738. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93739. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  93740. }
  93741. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  93742. this._webVRCamera.useStandingMatrix();
  93743. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  93744. // Create default button
  93745. if (!this._useCustomVRButton) {
  93746. this._btnVR = document.createElement("BUTTON");
  93747. this._btnVR.className = "babylonVRicon";
  93748. this._btnVR.id = "babylonVRiconbtn";
  93749. this._btnVR.title = "Click to switch to VR";
  93750. 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) }";
  93751. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  93752. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  93753. // css += ".babylonVRicon.vrdisplaysupported { }";
  93754. // css += ".babylonVRicon.vrdisplayready { }";
  93755. // css += ".babylonVRicon.vrdisplayrequesting { }";
  93756. var style = document.createElement('style');
  93757. style.appendChild(document.createTextNode(css));
  93758. document.getElementsByTagName('head')[0].appendChild(style);
  93759. this.moveButtonToBottomRight();
  93760. }
  93761. // VR button click event
  93762. if (this._btnVR) {
  93763. this._btnVR.addEventListener("click", function () {
  93764. if (!_this.isInVRMode) {
  93765. _this.enterVR();
  93766. }
  93767. else {
  93768. _this.exitVR();
  93769. }
  93770. });
  93771. }
  93772. // Window events
  93773. window.addEventListener("resize", this._onResize);
  93774. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  93775. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  93776. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  93777. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  93778. document.onmsfullscreenchange = this._onFullscreenChange;
  93779. // Display vr button when headset is connected
  93780. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93781. this.displayVRButton();
  93782. }
  93783. else {
  93784. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  93785. if (e.vrDisplay) {
  93786. _this.displayVRButton();
  93787. }
  93788. });
  93789. }
  93790. // Exiting VR mode using 'ESC' key on desktop
  93791. this._onKeyDown = function (event) {
  93792. if (event.keyCode === 27 && _this.isInVRMode) {
  93793. _this.exitVR();
  93794. }
  93795. };
  93796. document.addEventListener("keydown", this._onKeyDown);
  93797. // Exiting VR mode double tapping the touch screen
  93798. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  93799. if (_this.isInVRMode) {
  93800. _this.exitVR();
  93801. if (_this._fullscreenVRpresenting) {
  93802. _this._scene.getEngine().switchFullscreen(true);
  93803. }
  93804. }
  93805. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  93806. // Listen for WebVR display changes
  93807. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  93808. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  93809. this._onVRRequestPresentStart = function () {
  93810. _this._webVRrequesting = true;
  93811. _this.updateButtonVisibility();
  93812. };
  93813. this._onVRRequestPresentComplete = function (success) {
  93814. _this._webVRrequesting = false;
  93815. _this.updateButtonVisibility();
  93816. };
  93817. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  93818. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  93819. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  93820. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93821. scene.onDisposeObservable.add(function () {
  93822. _this.dispose();
  93823. });
  93824. // Gamepad connection events
  93825. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  93826. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  93827. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  93828. this.updateButtonVisibility();
  93829. //create easing functions
  93830. this._circleEase = new BABYLON.CircleEase();
  93831. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93832. if (this.webVROptions.floorMeshes) {
  93833. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  93834. }
  93835. }
  93836. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  93837. /** Return this.onEnteringVRObservable
  93838. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  93839. */
  93840. get: function () {
  93841. return this.onEnteringVRObservable;
  93842. },
  93843. enumerable: true,
  93844. configurable: true
  93845. });
  93846. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  93847. /** Return this.onExitingVRObservable
  93848. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  93849. */
  93850. get: function () {
  93851. return this.onExitingVRObservable;
  93852. },
  93853. enumerable: true,
  93854. configurable: true
  93855. });
  93856. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  93857. /** Return this.onControllerMeshLoadedObservable
  93858. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  93859. */
  93860. get: function () {
  93861. return this.onControllerMeshLoadedObservable;
  93862. },
  93863. enumerable: true,
  93864. configurable: true
  93865. });
  93866. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  93867. /**
  93868. * The mesh used to display where the user is going to teleport.
  93869. */
  93870. get: function () {
  93871. return this._teleportationTarget;
  93872. },
  93873. /**
  93874. * Sets the mesh to be used to display where the user is going to teleport.
  93875. */
  93876. set: function (value) {
  93877. if (value) {
  93878. value.name = "teleportationTarget";
  93879. this._isDefaultTeleportationTarget = false;
  93880. this._teleportationTarget = value;
  93881. }
  93882. },
  93883. enumerable: true,
  93884. configurable: true
  93885. });
  93886. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  93887. /**
  93888. * The mesh used to display where the user is selecting,
  93889. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  93890. * See http://doc.babylonjs.com/resources/baking_transformations
  93891. */
  93892. get: function () {
  93893. return this._cameraGazer._gazeTracker;
  93894. },
  93895. set: function (value) {
  93896. if (value) {
  93897. this._cameraGazer._gazeTracker = value;
  93898. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  93899. this._cameraGazer._gazeTracker.isPickable = false;
  93900. this._cameraGazer._gazeTracker.isVisible = false;
  93901. this._cameraGazer._gazeTracker.name = "gazeTracker";
  93902. if (this.leftController) {
  93903. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93904. }
  93905. if (this.rightController) {
  93906. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93907. }
  93908. }
  93909. },
  93910. enumerable: true,
  93911. configurable: true
  93912. });
  93913. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  93914. /**
  93915. * If the ray of the gaze should be displayed.
  93916. */
  93917. get: function () {
  93918. return this._displayGaze;
  93919. },
  93920. /**
  93921. * Sets if the ray of the gaze should be displayed.
  93922. */
  93923. set: function (value) {
  93924. this._displayGaze = value;
  93925. if (!value) {
  93926. this._cameraGazer._gazeTracker.isVisible = false;
  93927. if (this.leftController) {
  93928. this.leftController._gazeTracker.isVisible = false;
  93929. }
  93930. if (this.rightController) {
  93931. this.rightController._gazeTracker.isVisible = false;
  93932. }
  93933. }
  93934. },
  93935. enumerable: true,
  93936. configurable: true
  93937. });
  93938. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  93939. /**
  93940. * If the ray of the LaserPointer should be displayed.
  93941. */
  93942. get: function () {
  93943. return this._displayLaserPointer;
  93944. },
  93945. /**
  93946. * Sets if the ray of the LaserPointer should be displayed.
  93947. */
  93948. set: function (value) {
  93949. this._displayLaserPointer = value;
  93950. if (!value) {
  93951. if (this.rightController) {
  93952. this.rightController._deactivatePointer();
  93953. this.rightController._gazeTracker.isVisible = false;
  93954. }
  93955. if (this.leftController) {
  93956. this.leftController._deactivatePointer();
  93957. this.leftController._gazeTracker.isVisible = false;
  93958. }
  93959. }
  93960. else {
  93961. if (this.rightController) {
  93962. this.rightController._activatePointer();
  93963. }
  93964. if (this.leftController) {
  93965. this.leftController._activatePointer();
  93966. }
  93967. }
  93968. },
  93969. enumerable: true,
  93970. configurable: true
  93971. });
  93972. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  93973. /**
  93974. * The deviceOrientationCamera used as the camera when not in VR.
  93975. */
  93976. get: function () {
  93977. return this._deviceOrientationCamera;
  93978. },
  93979. enumerable: true,
  93980. configurable: true
  93981. });
  93982. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  93983. /**
  93984. * Based on the current WebVR support, returns the current VR camera used.
  93985. */
  93986. get: function () {
  93987. if (this._webVRready) {
  93988. return this._webVRCamera;
  93989. }
  93990. else {
  93991. return this._scene.activeCamera;
  93992. }
  93993. },
  93994. enumerable: true,
  93995. configurable: true
  93996. });
  93997. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93998. /**
  93999. * The webVRCamera which is used when in VR.
  94000. */
  94001. get: function () {
  94002. return this._webVRCamera;
  94003. },
  94004. enumerable: true,
  94005. configurable: true
  94006. });
  94007. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  94008. /**
  94009. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  94010. */
  94011. get: function () {
  94012. return this._vrDeviceOrientationCamera;
  94013. },
  94014. enumerable: true,
  94015. configurable: true
  94016. });
  94017. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  94018. get: function () {
  94019. var result = this._cameraGazer._teleportationRequestInitiated
  94020. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  94021. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  94022. return result;
  94023. },
  94024. enumerable: true,
  94025. configurable: true
  94026. });
  94027. // Raised when one of the controller has loaded successfully its associated default mesh
  94028. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  94029. if (this.leftController && this.leftController.webVRController == webVRController) {
  94030. if (webVRController.mesh) {
  94031. this.leftController._setLaserPointerParent(webVRController.mesh);
  94032. }
  94033. }
  94034. if (this.rightController && this.rightController.webVRController == webVRController) {
  94035. if (webVRController.mesh) {
  94036. this.rightController._setLaserPointerParent(webVRController.mesh);
  94037. }
  94038. }
  94039. try {
  94040. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  94041. }
  94042. catch (err) {
  94043. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  94044. }
  94045. };
  94046. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  94047. /**
  94048. * Gets a value indicating if we are currently in VR mode.
  94049. */
  94050. get: function () {
  94051. return this._webVRpresenting || this._fullscreenVRpresenting;
  94052. },
  94053. enumerable: true,
  94054. configurable: true
  94055. });
  94056. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  94057. var vrDisplay = this._scene.getEngine().getVRDevice();
  94058. if (vrDisplay) {
  94059. var wasPresenting = this._webVRpresenting;
  94060. // A VR display is connected
  94061. this._webVRpresenting = vrDisplay.isPresenting;
  94062. if (wasPresenting && !this._webVRpresenting)
  94063. this.exitVR();
  94064. }
  94065. else {
  94066. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  94067. }
  94068. this.updateButtonVisibility();
  94069. };
  94070. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  94071. this._webVRsupported = eventArgs.vrSupported;
  94072. this._webVRready = !!eventArgs.vrDisplay;
  94073. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  94074. this.updateButtonVisibility();
  94075. };
  94076. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  94077. if (this._canvas && !this._useCustomVRButton) {
  94078. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  94079. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  94080. }
  94081. };
  94082. VRExperienceHelper.prototype.displayVRButton = function () {
  94083. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  94084. document.body.appendChild(this._btnVR);
  94085. this._btnVRDisplayed = true;
  94086. }
  94087. };
  94088. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  94089. if (!this._btnVR || this._useCustomVRButton) {
  94090. return;
  94091. }
  94092. this._btnVR.className = "babylonVRicon";
  94093. if (this.isInVRMode) {
  94094. this._btnVR.className += " vrdisplaypresenting";
  94095. }
  94096. else {
  94097. if (this._webVRready)
  94098. this._btnVR.className += " vrdisplayready";
  94099. if (this._webVRsupported)
  94100. this._btnVR.className += " vrdisplaysupported";
  94101. if (this._webVRrequesting)
  94102. this._btnVR.className += " vrdisplayrequesting";
  94103. }
  94104. };
  94105. /**
  94106. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  94107. * Otherwise, will use the fullscreen API.
  94108. */
  94109. VRExperienceHelper.prototype.enterVR = function () {
  94110. if (this.onEnteringVRObservable) {
  94111. try {
  94112. this.onEnteringVRObservable.notifyObservers(this);
  94113. }
  94114. catch (err) {
  94115. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  94116. }
  94117. }
  94118. if (this._scene.activeCamera) {
  94119. this._position = this._scene.activeCamera.position.clone();
  94120. // make sure that we return to the last active camera
  94121. this._existingCamera = this._scene.activeCamera;
  94122. }
  94123. if (this._webVRrequesting)
  94124. return;
  94125. // If WebVR is supported and a headset is connected
  94126. if (this._webVRready) {
  94127. if (!this._webVRpresenting) {
  94128. this._webVRCamera.position = this._position;
  94129. this._scene.activeCamera = this._webVRCamera;
  94130. }
  94131. }
  94132. else if (this._vrDeviceOrientationCamera) {
  94133. this._vrDeviceOrientationCamera.position = this._position;
  94134. if (this._scene.activeCamera) {
  94135. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  94136. }
  94137. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  94138. this._scene.getEngine().switchFullscreen(true);
  94139. this.updateButtonVisibility();
  94140. }
  94141. if (this._scene.activeCamera && this._canvas) {
  94142. this._scene.activeCamera.attachControl(this._canvas);
  94143. }
  94144. if (this._interactionsEnabled) {
  94145. this._scene.registerBeforeRender(this.beforeRender);
  94146. }
  94147. };
  94148. /**
  94149. * Attempt to exit VR, or fullscreen.
  94150. */
  94151. VRExperienceHelper.prototype.exitVR = function () {
  94152. if (this.onExitingVRObservable) {
  94153. try {
  94154. this.onExitingVRObservable.notifyObservers(this);
  94155. }
  94156. catch (err) {
  94157. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  94158. }
  94159. }
  94160. if (this._webVRpresenting) {
  94161. this._scene.getEngine().disableVR();
  94162. }
  94163. if (this._scene.activeCamera) {
  94164. this._position = this._scene.activeCamera.position.clone();
  94165. }
  94166. if (this._deviceOrientationCamera) {
  94167. this._deviceOrientationCamera.position = this._position;
  94168. this._scene.activeCamera = this._deviceOrientationCamera;
  94169. if (this._canvas) {
  94170. this._scene.activeCamera.attachControl(this._canvas);
  94171. }
  94172. }
  94173. else if (this._existingCamera) {
  94174. this._existingCamera.position = this._position;
  94175. this._scene.activeCamera = this._existingCamera;
  94176. }
  94177. this.updateButtonVisibility();
  94178. if (this._interactionsEnabled) {
  94179. this._scene.unregisterBeforeRender(this.beforeRender);
  94180. }
  94181. // resize to update width and height when exiting vr exits fullscreen
  94182. this._scene.getEngine().resize();
  94183. };
  94184. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  94185. /**
  94186. * The position of the vr experience helper.
  94187. */
  94188. get: function () {
  94189. return this._position;
  94190. },
  94191. /**
  94192. * Sets the position of the vr experience helper.
  94193. */
  94194. set: function (value) {
  94195. this._position = value;
  94196. if (this._scene.activeCamera) {
  94197. this._scene.activeCamera.position = value;
  94198. }
  94199. },
  94200. enumerable: true,
  94201. configurable: true
  94202. });
  94203. /**
  94204. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  94205. */
  94206. VRExperienceHelper.prototype.enableInteractions = function () {
  94207. var _this = this;
  94208. if (!this._interactionsEnabled) {
  94209. this._interactionsRequested = true;
  94210. if (this.leftController) {
  94211. this._enableInteractionOnController(this.leftController);
  94212. }
  94213. if (this.rightController) {
  94214. this._enableInteractionOnController(this.rightController);
  94215. }
  94216. this.raySelectionPredicate = function (mesh) {
  94217. return mesh.isVisible && mesh.isPickable;
  94218. };
  94219. this.meshSelectionPredicate = function (mesh) {
  94220. return true;
  94221. };
  94222. this._raySelectionPredicate = function (mesh) {
  94223. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  94224. && mesh.name.indexOf("teleportationTarget") === -1
  94225. && mesh.name.indexOf("torusTeleportation") === -1)) {
  94226. return _this.raySelectionPredicate(mesh);
  94227. }
  94228. return false;
  94229. };
  94230. this._interactionsEnabled = true;
  94231. }
  94232. };
  94233. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  94234. get: function () {
  94235. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  94236. },
  94237. enumerable: true,
  94238. configurable: true
  94239. });
  94240. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  94241. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  94242. if (this._floorMeshesCollection[i].id === mesh.id) {
  94243. return true;
  94244. }
  94245. }
  94246. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  94247. return true;
  94248. }
  94249. return false;
  94250. };
  94251. /**
  94252. * Adds a floor mesh to be used for teleportation.
  94253. * @param floorMesh the mesh to be used for teleportation.
  94254. */
  94255. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  94256. if (!this._floorMeshesCollection) {
  94257. return;
  94258. }
  94259. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  94260. return;
  94261. }
  94262. this._floorMeshesCollection.push(floorMesh);
  94263. };
  94264. /**
  94265. * Removes a floor mesh from being used for teleportation.
  94266. * @param floorMesh the mesh to be removed.
  94267. */
  94268. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  94269. if (!this._floorMeshesCollection) {
  94270. return;
  94271. }
  94272. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  94273. if (meshIndex !== -1) {
  94274. this._floorMeshesCollection.splice(meshIndex, 1);
  94275. }
  94276. };
  94277. /**
  94278. * Enables interactions and teleportation using the VR controllers and gaze.
  94279. * @param vrTeleportationOptions options to modify teleportation behavior.
  94280. */
  94281. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  94282. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  94283. if (!this._teleportationInitialized) {
  94284. this._teleportationRequested = true;
  94285. this.enableInteractions();
  94286. if (vrTeleportationOptions.floorMeshName) {
  94287. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  94288. }
  94289. if (vrTeleportationOptions.floorMeshes) {
  94290. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  94291. }
  94292. if (this.leftController != null) {
  94293. this._enableTeleportationOnController(this.leftController);
  94294. }
  94295. if (this.rightController != null) {
  94296. this._enableTeleportationOnController(this.rightController);
  94297. }
  94298. // Creates an image processing post process for the vignette not relying
  94299. // on the main scene configuration for image processing to reduce setup and spaces
  94300. // (gamma/linear) conflicts.
  94301. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  94302. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  94303. imageProcessingConfiguration.vignetteEnabled = true;
  94304. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  94305. this._webVRCamera.detachPostProcess(this._postProcessMove);
  94306. this._teleportationInitialized = true;
  94307. if (this._isDefaultTeleportationTarget) {
  94308. this._createTeleportationCircles();
  94309. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  94310. }
  94311. }
  94312. };
  94313. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  94314. var _this = this;
  94315. var controllerMesh = controller.webVRController.mesh;
  94316. if (controllerMesh) {
  94317. controller._interactionsEnabled = true;
  94318. controller._activatePointer();
  94319. if (this.webVROptions.laserToggle) {
  94320. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  94321. // Enabling / disabling laserPointer
  94322. if (_this._displayLaserPointer && stateObject.value === 1) {
  94323. if (controller._activePointer) {
  94324. controller._deactivatePointer();
  94325. }
  94326. else {
  94327. controller._activatePointer();
  94328. }
  94329. if (_this.displayGaze) {
  94330. controller._gazeTracker.isVisible = controller._activePointer;
  94331. }
  94332. }
  94333. });
  94334. }
  94335. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  94336. var gazer = controller;
  94337. if (_this._noControllerIsActive) {
  94338. gazer = _this._cameraGazer;
  94339. }
  94340. if (!gazer._pointerDownOnMeshAsked) {
  94341. if (stateObject.value > _this._padSensibilityUp) {
  94342. gazer._selectionPointerDown();
  94343. }
  94344. }
  94345. else if (stateObject.value < _this._padSensibilityDown) {
  94346. gazer._selectionPointerUp();
  94347. }
  94348. });
  94349. }
  94350. };
  94351. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  94352. // Dont teleport if another gaze already requested teleportation
  94353. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  94354. return;
  94355. }
  94356. if (!gazer._teleportationRequestInitiated) {
  94357. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  94358. gazer._activatePointer();
  94359. gazer._teleportationRequestInitiated = true;
  94360. }
  94361. }
  94362. else {
  94363. // Listening to the proper controller values changes to confirm teleportation
  94364. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  94365. if (this._teleportActive) {
  94366. this._teleportCamera(this._haloCenter);
  94367. }
  94368. gazer._teleportationRequestInitiated = false;
  94369. }
  94370. }
  94371. };
  94372. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  94373. // Only rotate when user is not currently selecting a teleportation location
  94374. if (gazer._teleportationRequestInitiated) {
  94375. return;
  94376. }
  94377. if (!gazer._rotationLeftAsked) {
  94378. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  94379. gazer._rotationLeftAsked = true;
  94380. if (this._rotationAllowed) {
  94381. this._rotateCamera(false);
  94382. }
  94383. }
  94384. }
  94385. else {
  94386. if (stateObject.x > -this._padSensibilityDown) {
  94387. gazer._rotationLeftAsked = false;
  94388. }
  94389. }
  94390. if (!gazer._rotationRightAsked) {
  94391. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  94392. gazer._rotationRightAsked = true;
  94393. if (this._rotationAllowed) {
  94394. this._rotateCamera(true);
  94395. }
  94396. }
  94397. }
  94398. else {
  94399. if (stateObject.x < this._padSensibilityDown) {
  94400. gazer._rotationRightAsked = false;
  94401. }
  94402. }
  94403. };
  94404. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  94405. // Only teleport backwards when user is not currently selecting a teleportation location
  94406. if (gazer._teleportationRequestInitiated) {
  94407. return;
  94408. }
  94409. // Teleport backwards
  94410. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  94411. if (!gazer._teleportationBackRequestInitiated) {
  94412. if (!this.currentVRCamera) {
  94413. return;
  94414. }
  94415. // Get rotation and position of the current camera
  94416. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  94417. var position = this.currentVRCamera.position;
  94418. // If the camera has device position, use that instead
  94419. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  94420. rotation = this.currentVRCamera.deviceRotationQuaternion;
  94421. position = this.currentVRCamera.devicePosition;
  94422. }
  94423. // Get matrix with only the y rotation of the device rotation
  94424. rotation.toEulerAnglesToRef(this._workingVector);
  94425. this._workingVector.z = 0;
  94426. this._workingVector.x = 0;
  94427. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  94428. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  94429. // Rotate backwards ray by device rotation to cast at the ground behind the user
  94430. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  94431. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  94432. var ray = new BABYLON.Ray(position, this._workingVector);
  94433. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94434. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  94435. this._teleportCamera(hit.pickedPoint);
  94436. }
  94437. gazer._teleportationBackRequestInitiated = true;
  94438. }
  94439. }
  94440. else {
  94441. gazer._teleportationBackRequestInitiated = false;
  94442. }
  94443. };
  94444. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  94445. var _this = this;
  94446. var controllerMesh = controller.webVRController.mesh;
  94447. if (controllerMesh) {
  94448. if (!controller._interactionsEnabled) {
  94449. this._enableInteractionOnController(controller);
  94450. }
  94451. controller._interactionsEnabled = true;
  94452. controller._teleportationEnabled = true;
  94453. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  94454. controller._dpadPressed = false;
  94455. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  94456. controller._dpadPressed = stateObject.pressed;
  94457. if (!controller._dpadPressed) {
  94458. controller._rotationLeftAsked = false;
  94459. controller._rotationRightAsked = false;
  94460. controller._teleportationBackRequestInitiated = false;
  94461. }
  94462. });
  94463. }
  94464. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  94465. if (_this.teleportationEnabled) {
  94466. _this._checkTeleportBackwards(stateObject, controller);
  94467. _this._checkTeleportWithRay(stateObject, controller);
  94468. }
  94469. _this._checkRotate(stateObject, controller);
  94470. });
  94471. }
  94472. };
  94473. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  94474. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  94475. this._teleportationTarget.isPickable = false;
  94476. var length = 512;
  94477. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  94478. dynamicTexture.hasAlpha = true;
  94479. var context = dynamicTexture.getContext();
  94480. var centerX = length / 2;
  94481. var centerY = length / 2;
  94482. var radius = 200;
  94483. context.beginPath();
  94484. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  94485. context.fillStyle = this._teleportationFillColor;
  94486. context.fill();
  94487. context.lineWidth = 10;
  94488. context.strokeStyle = this._teleportationBorderColor;
  94489. context.stroke();
  94490. context.closePath();
  94491. dynamicTexture.update();
  94492. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  94493. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  94494. this._teleportationTarget.material = teleportationCircleMaterial;
  94495. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  94496. torus.isPickable = false;
  94497. torus.parent = this._teleportationTarget;
  94498. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  94499. var keys = [];
  94500. keys.push({
  94501. frame: 0,
  94502. value: 0
  94503. });
  94504. keys.push({
  94505. frame: 30,
  94506. value: 0.4
  94507. });
  94508. keys.push({
  94509. frame: 60,
  94510. value: 0
  94511. });
  94512. animationInnerCircle.setKeys(keys);
  94513. var easingFunction = new BABYLON.SineEase();
  94514. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  94515. animationInnerCircle.setEasingFunction(easingFunction);
  94516. torus.animations = [];
  94517. torus.animations.push(animationInnerCircle);
  94518. this._scene.beginAnimation(torus, 0, 60, true);
  94519. this._hideTeleportationTarget();
  94520. };
  94521. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  94522. this._teleportActive = true;
  94523. if (this._teleportationInitialized) {
  94524. this._teleportationTarget.isVisible = true;
  94525. if (this._isDefaultTeleportationTarget) {
  94526. this._teleportationTarget.getChildren()[0].isVisible = true;
  94527. }
  94528. }
  94529. };
  94530. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  94531. this._teleportActive = false;
  94532. if (this._teleportationInitialized) {
  94533. this._teleportationTarget.isVisible = false;
  94534. if (this._isDefaultTeleportationTarget) {
  94535. this._teleportationTarget.getChildren()[0].isVisible = false;
  94536. }
  94537. }
  94538. };
  94539. VRExperienceHelper.prototype._rotateCamera = function (right) {
  94540. var _this = this;
  94541. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94542. return;
  94543. }
  94544. if (right) {
  94545. this._rotationAngle++;
  94546. }
  94547. else {
  94548. this._rotationAngle--;
  94549. }
  94550. this.currentVRCamera.animations = [];
  94551. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  94552. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94553. var animationRotationKeys = [];
  94554. animationRotationKeys.push({
  94555. frame: 0,
  94556. value: this.currentVRCamera.rotationQuaternion
  94557. });
  94558. animationRotationKeys.push({
  94559. frame: 6,
  94560. value: target
  94561. });
  94562. animationRotation.setKeys(animationRotationKeys);
  94563. animationRotation.setEasingFunction(this._circleEase);
  94564. this.currentVRCamera.animations.push(animationRotation);
  94565. this._postProcessMove.animations = [];
  94566. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94567. var vignetteWeightKeys = [];
  94568. vignetteWeightKeys.push({
  94569. frame: 0,
  94570. value: 0
  94571. });
  94572. vignetteWeightKeys.push({
  94573. frame: 3,
  94574. value: 4
  94575. });
  94576. vignetteWeightKeys.push({
  94577. frame: 6,
  94578. value: 0
  94579. });
  94580. animationPP.setKeys(vignetteWeightKeys);
  94581. animationPP.setEasingFunction(this._circleEase);
  94582. this._postProcessMove.animations.push(animationPP);
  94583. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94584. var vignetteStretchKeys = [];
  94585. vignetteStretchKeys.push({
  94586. frame: 0,
  94587. value: 0
  94588. });
  94589. vignetteStretchKeys.push({
  94590. frame: 3,
  94591. value: 10
  94592. });
  94593. vignetteStretchKeys.push({
  94594. frame: 6,
  94595. value: 0
  94596. });
  94597. animationPP2.setKeys(vignetteStretchKeys);
  94598. animationPP2.setEasingFunction(this._circleEase);
  94599. this._postProcessMove.animations.push(animationPP2);
  94600. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94601. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94602. this._postProcessMove.samples = 4;
  94603. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94604. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  94605. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94606. });
  94607. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  94608. };
  94609. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  94610. if (hit.pickedPoint) {
  94611. if (gazer._teleportationRequestInitiated) {
  94612. this._displayTeleportationTarget();
  94613. this._haloCenter.copyFrom(hit.pickedPoint);
  94614. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  94615. }
  94616. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  94617. if (pickNormal) {
  94618. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94619. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94620. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  94621. }
  94622. this._teleportationTarget.position.y += 0.1;
  94623. }
  94624. };
  94625. VRExperienceHelper.prototype._teleportCamera = function (location) {
  94626. var _this = this;
  94627. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94628. return;
  94629. }
  94630. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  94631. // offset of the headset from the anchor.
  94632. if (this.webVRCamera.leftCamera) {
  94633. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  94634. this._workingVector.subtractInPlace(this.webVRCamera.position);
  94635. location.subtractToRef(this._workingVector, this._workingVector);
  94636. }
  94637. else {
  94638. this._workingVector.copyFrom(location);
  94639. }
  94640. // Add height to account for user's height offset
  94641. if (this.isInVRMode) {
  94642. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  94643. }
  94644. else {
  94645. this._workingVector.y += this._defaultHeight;
  94646. }
  94647. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  94648. // Create animation from the camera's position to the new location
  94649. this.currentVRCamera.animations = [];
  94650. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94651. var animationCameraTeleportationKeys = [{
  94652. frame: 0,
  94653. value: this.currentVRCamera.position
  94654. },
  94655. {
  94656. frame: 11,
  94657. value: this._workingVector
  94658. }
  94659. ];
  94660. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  94661. animationCameraTeleportation.setEasingFunction(this._circleEase);
  94662. this.currentVRCamera.animations.push(animationCameraTeleportation);
  94663. this._postProcessMove.animations = [];
  94664. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94665. var vignetteWeightKeys = [];
  94666. vignetteWeightKeys.push({
  94667. frame: 0,
  94668. value: 0
  94669. });
  94670. vignetteWeightKeys.push({
  94671. frame: 5,
  94672. value: 8
  94673. });
  94674. vignetteWeightKeys.push({
  94675. frame: 11,
  94676. value: 0
  94677. });
  94678. animationPP.setKeys(vignetteWeightKeys);
  94679. this._postProcessMove.animations.push(animationPP);
  94680. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94681. var vignetteStretchKeys = [];
  94682. vignetteStretchKeys.push({
  94683. frame: 0,
  94684. value: 0
  94685. });
  94686. vignetteStretchKeys.push({
  94687. frame: 5,
  94688. value: 10
  94689. });
  94690. vignetteStretchKeys.push({
  94691. frame: 11,
  94692. value: 0
  94693. });
  94694. animationPP2.setKeys(vignetteStretchKeys);
  94695. this._postProcessMove.animations.push(animationPP2);
  94696. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94697. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94698. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94699. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  94700. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94701. });
  94702. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  94703. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  94704. });
  94705. this._hideTeleportationTarget();
  94706. };
  94707. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  94708. if (normal) {
  94709. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  94710. if (angle < Math.PI / 2) {
  94711. normal.scaleInPlace(-1);
  94712. }
  94713. }
  94714. return normal;
  94715. };
  94716. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  94717. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94718. return;
  94719. }
  94720. var ray = gazer._getForwardRay(this._rayLength);
  94721. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94722. if (hit) {
  94723. // Populate the contrllers mesh that can be used for drag/drop
  94724. if (gazer._laserPointer) {
  94725. hit.originMesh = gazer._laserPointer.parent;
  94726. }
  94727. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  94728. }
  94729. gazer._currentHit = hit;
  94730. // Moving the gazeTracker on the mesh face targetted
  94731. if (hit && hit.pickedPoint) {
  94732. if (this._displayGaze) {
  94733. var multiplier = 1;
  94734. gazer._gazeTracker.isVisible = true;
  94735. if (gazer._isActionableMesh) {
  94736. multiplier = 3;
  94737. }
  94738. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  94739. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  94740. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  94741. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  94742. // To avoid z-fighting
  94743. var deltaFighting = 0.002;
  94744. if (pickNormal) {
  94745. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94746. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94747. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  94748. }
  94749. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  94750. if (gazer._gazeTracker.position.x < 0) {
  94751. gazer._gazeTracker.position.x += deltaFighting;
  94752. }
  94753. else {
  94754. gazer._gazeTracker.position.x -= deltaFighting;
  94755. }
  94756. if (gazer._gazeTracker.position.y < 0) {
  94757. gazer._gazeTracker.position.y += deltaFighting;
  94758. }
  94759. else {
  94760. gazer._gazeTracker.position.y -= deltaFighting;
  94761. }
  94762. if (gazer._gazeTracker.position.z < 0) {
  94763. gazer._gazeTracker.position.z += deltaFighting;
  94764. }
  94765. else {
  94766. gazer._gazeTracker.position.z -= deltaFighting;
  94767. }
  94768. }
  94769. // Changing the size of the laser pointer based on the distance from the targetted point
  94770. gazer._updatePointerDistance(hit.distance);
  94771. }
  94772. else {
  94773. gazer._updatePointerDistance();
  94774. gazer._gazeTracker.isVisible = false;
  94775. }
  94776. if (hit && hit.pickedMesh) {
  94777. // The object selected is the floor, we're in a teleportation scenario
  94778. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  94779. // Moving the teleportation area to this targetted point
  94780. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  94781. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  94782. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94783. }
  94784. gazer._currentMeshSelected = null;
  94785. if (gazer._teleportationRequestInitiated) {
  94786. this._moveTeleportationSelectorTo(hit, gazer, ray);
  94787. }
  94788. return;
  94789. }
  94790. // If not, we're in a selection scenario
  94791. //this._teleportationAllowed = false;
  94792. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  94793. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  94794. this.onNewMeshPicked.notifyObservers(hit);
  94795. gazer._currentMeshSelected = hit.pickedMesh;
  94796. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  94797. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  94798. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  94799. gazer._isActionableMesh = true;
  94800. }
  94801. else {
  94802. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94803. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94804. gazer._isActionableMesh = false;
  94805. }
  94806. try {
  94807. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  94808. }
  94809. catch (err) {
  94810. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  94811. }
  94812. }
  94813. else {
  94814. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94815. gazer._currentMeshSelected = null;
  94816. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94817. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94818. }
  94819. }
  94820. }
  94821. else {
  94822. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94823. gazer._currentMeshSelected = null;
  94824. //this._teleportationAllowed = false;
  94825. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94826. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94827. }
  94828. };
  94829. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  94830. if (mesh) {
  94831. this.onSelectedMeshUnselected.notifyObservers(mesh);
  94832. }
  94833. };
  94834. /**
  94835. * Sets the color of the laser ray from the vr controllers.
  94836. * @param color new color for the ray.
  94837. */
  94838. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  94839. if (this.leftController) {
  94840. this.leftController._setLaserPointerColor(color);
  94841. }
  94842. if (this.rightController) {
  94843. this.rightController._setLaserPointerColor(color);
  94844. }
  94845. };
  94846. /**
  94847. * Sets the color of the ray from the vr headsets gaze.
  94848. * @param color new color for the ray.
  94849. */
  94850. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  94851. if (!this._cameraGazer._gazeTracker.material) {
  94852. return;
  94853. }
  94854. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  94855. if (this.leftController) {
  94856. this.leftController._gazeTracker.material.emissiveColor = color;
  94857. }
  94858. if (this.rightController) {
  94859. this.rightController._gazeTracker.material.emissiveColor = color;
  94860. }
  94861. };
  94862. /**
  94863. * Exits VR and disposes of the vr experience helper
  94864. */
  94865. VRExperienceHelper.prototype.dispose = function () {
  94866. if (this.isInVRMode) {
  94867. this.exitVR();
  94868. }
  94869. if (this._postProcessMove) {
  94870. this._postProcessMove.dispose();
  94871. }
  94872. if (this._webVRCamera) {
  94873. this._webVRCamera.dispose();
  94874. }
  94875. if (this._vrDeviceOrientationCamera) {
  94876. this._vrDeviceOrientationCamera.dispose();
  94877. }
  94878. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  94879. document.body.removeChild(this._btnVR);
  94880. }
  94881. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  94882. this._deviceOrientationCamera.dispose();
  94883. }
  94884. if (this._cameraGazer) {
  94885. this._cameraGazer.dispose();
  94886. }
  94887. if (this.leftController) {
  94888. this.leftController.dispose();
  94889. }
  94890. if (this.rightController) {
  94891. this.rightController.dispose();
  94892. }
  94893. if (this._teleportationTarget) {
  94894. this._teleportationTarget.dispose();
  94895. }
  94896. this._floorMeshesCollection = [];
  94897. document.removeEventListener("keydown", this._onKeyDown);
  94898. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94899. window.removeEventListener("resize", this._onResize);
  94900. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  94901. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  94902. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  94903. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  94904. document.onmsfullscreenchange = null;
  94905. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  94906. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  94907. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  94908. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94909. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  94910. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  94911. this._scene.unregisterBeforeRender(this.beforeRender);
  94912. };
  94913. /**
  94914. * Gets the name of the VRExperienceHelper class
  94915. * @returns "VRExperienceHelper"
  94916. */
  94917. VRExperienceHelper.prototype.getClassName = function () {
  94918. return "VRExperienceHelper";
  94919. };
  94920. return VRExperienceHelper;
  94921. }());
  94922. BABYLON.VRExperienceHelper = VRExperienceHelper;
  94923. })(BABYLON || (BABYLON = {}));
  94924. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  94925. // Mainly based on these 2 articles :
  94926. // 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
  94927. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  94928. var BABYLON;
  94929. (function (BABYLON) {
  94930. /**
  94931. * Defines the potential axis of a Joystick
  94932. */
  94933. var JoystickAxis;
  94934. (function (JoystickAxis) {
  94935. /** X axis */
  94936. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  94937. /** Y axis */
  94938. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  94939. /** Z axis */
  94940. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  94941. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  94942. /**
  94943. * Class used to define virtual joystick (used in touch mode)
  94944. */
  94945. var VirtualJoystick = /** @class */ (function () {
  94946. /**
  94947. * Creates a new virtual joystick
  94948. * @param leftJoystick defines that the joystick is for left hand (false by default)
  94949. */
  94950. function VirtualJoystick(leftJoystick) {
  94951. var _this = this;
  94952. if (leftJoystick) {
  94953. this._leftJoystick = true;
  94954. }
  94955. else {
  94956. this._leftJoystick = false;
  94957. }
  94958. VirtualJoystick._globalJoystickIndex++;
  94959. // By default left & right arrow keys are moving the X
  94960. // and up & down keys are moving the Y
  94961. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94962. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94963. this.reverseLeftRight = false;
  94964. this.reverseUpDown = false;
  94965. // collections of pointers
  94966. this._touches = new BABYLON.StringDictionary();
  94967. this.deltaPosition = BABYLON.Vector3.Zero();
  94968. this._joystickSensibility = 25;
  94969. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94970. this._onResize = function (evt) {
  94971. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94972. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94973. if (VirtualJoystick.vjCanvas) {
  94974. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  94975. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  94976. }
  94977. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  94978. };
  94979. // injecting a canvas element on top of the canvas 3D game
  94980. if (!VirtualJoystick.vjCanvas) {
  94981. window.addEventListener("resize", this._onResize, false);
  94982. VirtualJoystick.vjCanvas = document.createElement("canvas");
  94983. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94984. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94985. VirtualJoystick.vjCanvas.width = window.innerWidth;
  94986. VirtualJoystick.vjCanvas.height = window.innerHeight;
  94987. VirtualJoystick.vjCanvas.style.width = "100%";
  94988. VirtualJoystick.vjCanvas.style.height = "100%";
  94989. VirtualJoystick.vjCanvas.style.position = "absolute";
  94990. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94991. VirtualJoystick.vjCanvas.style.top = "0px";
  94992. VirtualJoystick.vjCanvas.style.left = "0px";
  94993. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94994. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94995. // Support for jQuery PEP polyfill
  94996. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94997. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94998. if (!context) {
  94999. throw new Error("Unable to create canvas for virtual joystick");
  95000. }
  95001. VirtualJoystick.vjCanvasContext = context;
  95002. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  95003. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95004. document.body.appendChild(VirtualJoystick.vjCanvas);
  95005. }
  95006. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  95007. this.pressed = false;
  95008. // default joystick color
  95009. this._joystickColor = "cyan";
  95010. this._joystickPointerID = -1;
  95011. // current joystick position
  95012. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  95013. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  95014. // origin joystick position
  95015. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  95016. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  95017. this._onPointerDownHandlerRef = function (evt) {
  95018. _this._onPointerDown(evt);
  95019. };
  95020. this._onPointerMoveHandlerRef = function (evt) {
  95021. _this._onPointerMove(evt);
  95022. };
  95023. this._onPointerUpHandlerRef = function (evt) {
  95024. _this._onPointerUp(evt);
  95025. };
  95026. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  95027. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  95028. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  95029. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  95030. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  95031. evt.preventDefault(); // Disables system menu
  95032. }, false);
  95033. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95034. }
  95035. /**
  95036. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  95037. * @param newJoystickSensibility defines the new sensibility
  95038. */
  95039. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  95040. this._joystickSensibility = newJoystickSensibility;
  95041. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  95042. };
  95043. VirtualJoystick.prototype._onPointerDown = function (e) {
  95044. var positionOnScreenCondition;
  95045. e.preventDefault();
  95046. if (this._leftJoystick === true) {
  95047. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  95048. }
  95049. else {
  95050. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  95051. }
  95052. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  95053. // First contact will be dedicated to the virtual joystick
  95054. this._joystickPointerID = e.pointerId;
  95055. this._joystickPointerStartPos.x = e.clientX;
  95056. this._joystickPointerStartPos.y = e.clientY;
  95057. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  95058. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  95059. this._deltaJoystickVector.x = 0;
  95060. this._deltaJoystickVector.y = 0;
  95061. this.pressed = true;
  95062. this._touches.add(e.pointerId.toString(), e);
  95063. }
  95064. else {
  95065. // You can only trigger the action buttons with a joystick declared
  95066. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  95067. this._action();
  95068. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  95069. }
  95070. }
  95071. };
  95072. VirtualJoystick.prototype._onPointerMove = function (e) {
  95073. // If the current pointer is the one associated to the joystick (first touch contact)
  95074. if (this._joystickPointerID == e.pointerId) {
  95075. this._joystickPointerPos.x = e.clientX;
  95076. this._joystickPointerPos.y = e.clientY;
  95077. this._deltaJoystickVector = this._joystickPointerPos.clone();
  95078. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  95079. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  95080. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  95081. switch (this._axisTargetedByLeftAndRight) {
  95082. case JoystickAxis.X:
  95083. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  95084. break;
  95085. case JoystickAxis.Y:
  95086. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  95087. break;
  95088. case JoystickAxis.Z:
  95089. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  95090. break;
  95091. }
  95092. var directionUpDown = this.reverseUpDown ? 1 : -1;
  95093. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  95094. switch (this._axisTargetedByUpAndDown) {
  95095. case JoystickAxis.X:
  95096. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  95097. break;
  95098. case JoystickAxis.Y:
  95099. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  95100. break;
  95101. case JoystickAxis.Z:
  95102. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  95103. break;
  95104. }
  95105. }
  95106. else {
  95107. var data = this._touches.get(e.pointerId.toString());
  95108. if (data) {
  95109. data.x = e.clientX;
  95110. data.y = e.clientY;
  95111. }
  95112. }
  95113. };
  95114. VirtualJoystick.prototype._onPointerUp = function (e) {
  95115. if (this._joystickPointerID == e.pointerId) {
  95116. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  95117. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  95118. this._joystickPointerID = -1;
  95119. this.pressed = false;
  95120. }
  95121. else {
  95122. var touch = this._touches.get(e.pointerId.toString());
  95123. if (touch) {
  95124. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95125. }
  95126. }
  95127. this._deltaJoystickVector.x = 0;
  95128. this._deltaJoystickVector.y = 0;
  95129. this._touches.remove(e.pointerId.toString());
  95130. };
  95131. /**
  95132. * Change the color of the virtual joystick
  95133. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  95134. */
  95135. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  95136. this._joystickColor = newColor;
  95137. };
  95138. /**
  95139. * Defines a callback to call when the joystick is touched
  95140. * @param action defines the callback
  95141. */
  95142. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  95143. this._action = action;
  95144. };
  95145. /**
  95146. * Defines which axis you'd like to control for left & right
  95147. * @param axis defines the axis to use
  95148. */
  95149. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  95150. switch (axis) {
  95151. case JoystickAxis.X:
  95152. case JoystickAxis.Y:
  95153. case JoystickAxis.Z:
  95154. this._axisTargetedByLeftAndRight = axis;
  95155. break;
  95156. default:
  95157. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  95158. break;
  95159. }
  95160. };
  95161. /**
  95162. * Defines which axis you'd like to control for up & down
  95163. * @param axis defines the axis to use
  95164. */
  95165. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  95166. switch (axis) {
  95167. case JoystickAxis.X:
  95168. case JoystickAxis.Y:
  95169. case JoystickAxis.Z:
  95170. this._axisTargetedByUpAndDown = axis;
  95171. break;
  95172. default:
  95173. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95174. break;
  95175. }
  95176. };
  95177. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  95178. var _this = this;
  95179. if (this.pressed) {
  95180. this._touches.forEach(function (key, touch) {
  95181. if (touch.pointerId === _this._joystickPointerID) {
  95182. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  95183. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  95184. VirtualJoystick.vjCanvasContext.beginPath();
  95185. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95186. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95187. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  95188. VirtualJoystick.vjCanvasContext.stroke();
  95189. VirtualJoystick.vjCanvasContext.closePath();
  95190. VirtualJoystick.vjCanvasContext.beginPath();
  95191. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95192. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95193. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  95194. VirtualJoystick.vjCanvasContext.stroke();
  95195. VirtualJoystick.vjCanvasContext.closePath();
  95196. VirtualJoystick.vjCanvasContext.beginPath();
  95197. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95198. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  95199. VirtualJoystick.vjCanvasContext.stroke();
  95200. VirtualJoystick.vjCanvasContext.closePath();
  95201. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  95202. }
  95203. else {
  95204. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95205. VirtualJoystick.vjCanvasContext.beginPath();
  95206. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  95207. VirtualJoystick.vjCanvasContext.beginPath();
  95208. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  95209. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95210. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  95211. VirtualJoystick.vjCanvasContext.stroke();
  95212. VirtualJoystick.vjCanvasContext.closePath();
  95213. touch.prevX = touch.x;
  95214. touch.prevY = touch.y;
  95215. }
  95216. ;
  95217. });
  95218. }
  95219. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95220. };
  95221. /**
  95222. * Release internal HTML canvas
  95223. */
  95224. VirtualJoystick.prototype.releaseCanvas = function () {
  95225. if (VirtualJoystick.vjCanvas) {
  95226. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  95227. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  95228. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  95229. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  95230. window.removeEventListener("resize", this._onResize);
  95231. document.body.removeChild(VirtualJoystick.vjCanvas);
  95232. VirtualJoystick.vjCanvas = null;
  95233. }
  95234. };
  95235. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  95236. VirtualJoystick._globalJoystickIndex = 0;
  95237. return VirtualJoystick;
  95238. }());
  95239. BABYLON.VirtualJoystick = VirtualJoystick;
  95240. })(BABYLON || (BABYLON = {}));
  95241. //# sourceMappingURL=babylon.virtualJoystick.js.map
  95242. var BABYLON;
  95243. (function (BABYLON) {
  95244. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  95245. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  95246. });
  95247. // We're mainly based on the logic defined into the FreeCamera code
  95248. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  95249. __extends(VirtualJoysticksCamera, _super);
  95250. function VirtualJoysticksCamera(name, position, scene) {
  95251. var _this = _super.call(this, name, position, scene) || this;
  95252. _this.inputs.addVirtualJoystick();
  95253. return _this;
  95254. }
  95255. VirtualJoysticksCamera.prototype.getClassName = function () {
  95256. return "VirtualJoysticksCamera";
  95257. };
  95258. return VirtualJoysticksCamera;
  95259. }(BABYLON.FreeCamera));
  95260. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  95261. })(BABYLON || (BABYLON = {}));
  95262. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  95263. var BABYLON;
  95264. (function (BABYLON) {
  95265. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  95266. function FreeCameraVirtualJoystickInput() {
  95267. }
  95268. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  95269. return this._leftjoystick;
  95270. };
  95271. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  95272. return this._rightjoystick;
  95273. };
  95274. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  95275. if (this._leftjoystick) {
  95276. var camera = this.camera;
  95277. var speed = camera._computeLocalCameraSpeed() * 50;
  95278. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  95279. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  95280. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  95281. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  95282. if (!this._leftjoystick.pressed) {
  95283. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  95284. }
  95285. if (!this._rightjoystick.pressed) {
  95286. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  95287. }
  95288. }
  95289. };
  95290. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  95291. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  95292. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  95293. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  95294. this._leftjoystick.setJoystickSensibility(0.15);
  95295. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  95296. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  95297. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  95298. this._rightjoystick.reverseUpDown = true;
  95299. this._rightjoystick.setJoystickSensibility(0.05);
  95300. this._rightjoystick.setJoystickColor("yellow");
  95301. };
  95302. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  95303. this._leftjoystick.releaseCanvas();
  95304. this._rightjoystick.releaseCanvas();
  95305. };
  95306. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  95307. return "FreeCameraVirtualJoystickInput";
  95308. };
  95309. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  95310. return "virtualJoystick";
  95311. };
  95312. return FreeCameraVirtualJoystickInput;
  95313. }());
  95314. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  95315. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  95316. })(BABYLON || (BABYLON = {}));
  95317. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  95318. var BABYLON;
  95319. (function (BABYLON) {
  95320. var SimplificationSettings = /** @class */ (function () {
  95321. function SimplificationSettings(quality, distance, optimizeMesh) {
  95322. this.quality = quality;
  95323. this.distance = distance;
  95324. this.optimizeMesh = optimizeMesh;
  95325. }
  95326. return SimplificationSettings;
  95327. }());
  95328. BABYLON.SimplificationSettings = SimplificationSettings;
  95329. var SimplificationQueue = /** @class */ (function () {
  95330. function SimplificationQueue() {
  95331. this.running = false;
  95332. this._simplificationArray = [];
  95333. }
  95334. SimplificationQueue.prototype.addTask = function (task) {
  95335. this._simplificationArray.push(task);
  95336. };
  95337. SimplificationQueue.prototype.executeNext = function () {
  95338. var task = this._simplificationArray.pop();
  95339. if (task) {
  95340. this.running = true;
  95341. this.runSimplification(task);
  95342. }
  95343. else {
  95344. this.running = false;
  95345. }
  95346. };
  95347. SimplificationQueue.prototype.runSimplification = function (task) {
  95348. var _this = this;
  95349. if (task.parallelProcessing) {
  95350. //parallel simplifier
  95351. task.settings.forEach(function (setting) {
  95352. var simplifier = _this.getSimplifier(task);
  95353. simplifier.simplify(setting, function (newMesh) {
  95354. task.mesh.addLODLevel(setting.distance, newMesh);
  95355. newMesh.isVisible = true;
  95356. //check if it is the last
  95357. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  95358. //all done, run the success callback.
  95359. task.successCallback();
  95360. }
  95361. _this.executeNext();
  95362. });
  95363. });
  95364. }
  95365. else {
  95366. //single simplifier.
  95367. var simplifier = this.getSimplifier(task);
  95368. var runDecimation = function (setting, callback) {
  95369. simplifier.simplify(setting, function (newMesh) {
  95370. task.mesh.addLODLevel(setting.distance, newMesh);
  95371. newMesh.isVisible = true;
  95372. //run the next quality level
  95373. callback();
  95374. });
  95375. };
  95376. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  95377. runDecimation(task.settings[loop.index], function () {
  95378. loop.executeNext();
  95379. });
  95380. }, function () {
  95381. //execution ended, run the success callback.
  95382. if (task.successCallback) {
  95383. task.successCallback();
  95384. }
  95385. _this.executeNext();
  95386. });
  95387. }
  95388. };
  95389. SimplificationQueue.prototype.getSimplifier = function (task) {
  95390. switch (task.simplificationType) {
  95391. case SimplificationType.QUADRATIC:
  95392. default:
  95393. return new QuadraticErrorSimplification(task.mesh);
  95394. }
  95395. };
  95396. return SimplificationQueue;
  95397. }());
  95398. BABYLON.SimplificationQueue = SimplificationQueue;
  95399. /**
  95400. * The implemented types of simplification
  95401. * At the moment only Quadratic Error Decimation is implemented
  95402. */
  95403. var SimplificationType;
  95404. (function (SimplificationType) {
  95405. /** Quadratic error decimation */
  95406. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  95407. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  95408. var DecimationTriangle = /** @class */ (function () {
  95409. function DecimationTriangle(vertices) {
  95410. this.vertices = vertices;
  95411. this.error = new Array(4);
  95412. this.deleted = false;
  95413. this.isDirty = false;
  95414. this.deletePending = false;
  95415. this.borderFactor = 0;
  95416. }
  95417. return DecimationTriangle;
  95418. }());
  95419. BABYLON.DecimationTriangle = DecimationTriangle;
  95420. var DecimationVertex = /** @class */ (function () {
  95421. function DecimationVertex(position, id) {
  95422. this.position = position;
  95423. this.id = id;
  95424. this.isBorder = true;
  95425. this.q = new QuadraticMatrix();
  95426. this.triangleCount = 0;
  95427. this.triangleStart = 0;
  95428. this.originalOffsets = [];
  95429. }
  95430. DecimationVertex.prototype.updatePosition = function (newPosition) {
  95431. this.position.copyFrom(newPosition);
  95432. };
  95433. return DecimationVertex;
  95434. }());
  95435. BABYLON.DecimationVertex = DecimationVertex;
  95436. var QuadraticMatrix = /** @class */ (function () {
  95437. function QuadraticMatrix(data) {
  95438. this.data = new Array(10);
  95439. for (var i = 0; i < 10; ++i) {
  95440. if (data && data[i]) {
  95441. this.data[i] = data[i];
  95442. }
  95443. else {
  95444. this.data[i] = 0;
  95445. }
  95446. }
  95447. }
  95448. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  95449. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  95450. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  95451. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  95452. return det;
  95453. };
  95454. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  95455. for (var i = 0; i < 10; ++i) {
  95456. this.data[i] += matrix.data[i];
  95457. }
  95458. };
  95459. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  95460. for (var i = 0; i < 10; ++i) {
  95461. this.data[i] += data[i];
  95462. }
  95463. };
  95464. QuadraticMatrix.prototype.add = function (matrix) {
  95465. var m = new QuadraticMatrix();
  95466. for (var i = 0; i < 10; ++i) {
  95467. m.data[i] = this.data[i] + matrix.data[i];
  95468. }
  95469. return m;
  95470. };
  95471. QuadraticMatrix.FromData = function (a, b, c, d) {
  95472. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  95473. };
  95474. //returning an array to avoid garbage collection
  95475. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  95476. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  95477. };
  95478. return QuadraticMatrix;
  95479. }());
  95480. BABYLON.QuadraticMatrix = QuadraticMatrix;
  95481. var Reference = /** @class */ (function () {
  95482. function Reference(vertexId, triangleId) {
  95483. this.vertexId = vertexId;
  95484. this.triangleId = triangleId;
  95485. }
  95486. return Reference;
  95487. }());
  95488. BABYLON.Reference = Reference;
  95489. /**
  95490. * An implementation of the Quadratic Error simplification algorithm.
  95491. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  95492. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  95493. * @author RaananW
  95494. */
  95495. var QuadraticErrorSimplification = /** @class */ (function () {
  95496. function QuadraticErrorSimplification(_mesh) {
  95497. this._mesh = _mesh;
  95498. this.syncIterations = 5000;
  95499. this.aggressiveness = 7;
  95500. this.decimationIterations = 100;
  95501. this.boundingBoxEpsilon = BABYLON.Epsilon;
  95502. }
  95503. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  95504. var _this = this;
  95505. this.initDecimatedMesh();
  95506. //iterating through the submeshes array, one after the other.
  95507. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  95508. _this.initWithMesh(loop.index, function () {
  95509. _this.runDecimation(settings, loop.index, function () {
  95510. loop.executeNext();
  95511. });
  95512. }, settings.optimizeMesh);
  95513. }, function () {
  95514. setTimeout(function () {
  95515. successCallback(_this._reconstructedMesh);
  95516. }, 0);
  95517. });
  95518. };
  95519. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  95520. var _this = this;
  95521. var targetCount = ~~(this.triangles.length * settings.quality);
  95522. var deletedTriangles = 0;
  95523. var triangleCount = this.triangles.length;
  95524. var iterationFunction = function (iteration, callback) {
  95525. setTimeout(function () {
  95526. if (iteration % 5 === 0) {
  95527. _this.updateMesh(iteration === 0);
  95528. }
  95529. for (var i = 0; i < _this.triangles.length; ++i) {
  95530. _this.triangles[i].isDirty = false;
  95531. }
  95532. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  95533. var trianglesIterator = function (i) {
  95534. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  95535. var t = _this.triangles[tIdx];
  95536. if (!t)
  95537. return;
  95538. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  95539. return;
  95540. }
  95541. for (var j = 0; j < 3; ++j) {
  95542. if (t.error[j] < threshold) {
  95543. var deleted0 = [];
  95544. var deleted1 = [];
  95545. var v0 = t.vertices[j];
  95546. var v1 = t.vertices[(j + 1) % 3];
  95547. if (v0.isBorder || v1.isBorder)
  95548. continue;
  95549. var p = BABYLON.Vector3.Zero();
  95550. var n = BABYLON.Vector3.Zero();
  95551. var uv = BABYLON.Vector2.Zero();
  95552. var color = new BABYLON.Color4(0, 0, 0, 1);
  95553. _this.calculateError(v0, v1, p, n, uv, color);
  95554. var delTr = new Array();
  95555. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  95556. continue;
  95557. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  95558. continue;
  95559. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  95560. continue;
  95561. var uniqueArray = new Array();
  95562. delTr.forEach(function (deletedT) {
  95563. if (uniqueArray.indexOf(deletedT) === -1) {
  95564. deletedT.deletePending = true;
  95565. uniqueArray.push(deletedT);
  95566. }
  95567. });
  95568. if (uniqueArray.length % 2 !== 0) {
  95569. continue;
  95570. }
  95571. v0.q = v1.q.add(v0.q);
  95572. v0.updatePosition(p);
  95573. var tStart = _this.references.length;
  95574. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  95575. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  95576. var tCount = _this.references.length - tStart;
  95577. if (tCount <= v0.triangleCount) {
  95578. if (tCount) {
  95579. for (var c = 0; c < tCount; c++) {
  95580. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  95581. }
  95582. }
  95583. }
  95584. else {
  95585. v0.triangleStart = tStart;
  95586. }
  95587. v0.triangleCount = tCount;
  95588. break;
  95589. }
  95590. }
  95591. };
  95592. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  95593. }, 0);
  95594. };
  95595. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  95596. if (triangleCount - deletedTriangles <= targetCount)
  95597. loop.breakLoop();
  95598. else {
  95599. iterationFunction(loop.index, function () {
  95600. loop.executeNext();
  95601. });
  95602. }
  95603. }, function () {
  95604. setTimeout(function () {
  95605. //reconstruct this part of the mesh
  95606. _this.reconstructMesh(submeshIndex);
  95607. successCallback();
  95608. }, 0);
  95609. });
  95610. };
  95611. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  95612. var _this = this;
  95613. this.vertices = [];
  95614. this.triangles = [];
  95615. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95616. var indices = this._mesh.getIndices();
  95617. var submesh = this._mesh.subMeshes[submeshIndex];
  95618. var findInVertices = function (positionToSearch) {
  95619. if (optimizeMesh) {
  95620. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  95621. if (_this.vertices[ii].position.equals(positionToSearch)) {
  95622. return _this.vertices[ii];
  95623. }
  95624. }
  95625. }
  95626. return null;
  95627. };
  95628. var vertexReferences = [];
  95629. var vertexInit = function (i) {
  95630. if (!positionData) {
  95631. return;
  95632. }
  95633. var offset = i + submesh.verticesStart;
  95634. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  95635. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  95636. vertex.originalOffsets.push(offset);
  95637. if (vertex.id === _this.vertices.length) {
  95638. _this.vertices.push(vertex);
  95639. }
  95640. vertexReferences.push(vertex.id);
  95641. };
  95642. //var totalVertices = mesh.getTotalVertices();
  95643. var totalVertices = submesh.verticesCount;
  95644. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  95645. var indicesInit = function (i) {
  95646. if (!indices) {
  95647. return;
  95648. }
  95649. var offset = (submesh.indexStart / 3) + i;
  95650. var pos = (offset * 3);
  95651. var i0 = indices[pos + 0];
  95652. var i1 = indices[pos + 1];
  95653. var i2 = indices[pos + 2];
  95654. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  95655. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  95656. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  95657. var triangle = new DecimationTriangle([v0, v1, v2]);
  95658. triangle.originalOffset = pos;
  95659. _this.triangles.push(triangle);
  95660. };
  95661. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  95662. _this.init(callback);
  95663. });
  95664. });
  95665. };
  95666. QuadraticErrorSimplification.prototype.init = function (callback) {
  95667. var _this = this;
  95668. var triangleInit1 = function (i) {
  95669. var t = _this.triangles[i];
  95670. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  95671. for (var j = 0; j < 3; j++) {
  95672. 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))));
  95673. }
  95674. };
  95675. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  95676. var triangleInit2 = function (i) {
  95677. var t = _this.triangles[i];
  95678. for (var j = 0; j < 3; ++j) {
  95679. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  95680. }
  95681. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95682. };
  95683. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  95684. callback();
  95685. });
  95686. });
  95687. };
  95688. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  95689. var newTriangles = [];
  95690. var i;
  95691. for (i = 0; i < this.vertices.length; ++i) {
  95692. this.vertices[i].triangleCount = 0;
  95693. }
  95694. var t;
  95695. var j;
  95696. for (i = 0; i < this.triangles.length; ++i) {
  95697. if (!this.triangles[i].deleted) {
  95698. t = this.triangles[i];
  95699. for (j = 0; j < 3; ++j) {
  95700. t.vertices[j].triangleCount = 1;
  95701. }
  95702. newTriangles.push(t);
  95703. }
  95704. }
  95705. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  95706. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  95707. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  95708. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  95709. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  95710. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  95711. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  95712. var vertexCount = 0;
  95713. for (i = 0; i < this.vertices.length; ++i) {
  95714. var vertex = this.vertices[i];
  95715. vertex.id = vertexCount;
  95716. if (vertex.triangleCount) {
  95717. vertex.originalOffsets.forEach(function (originalOffset) {
  95718. if (!normalData) {
  95719. return;
  95720. }
  95721. newPositionData.push(vertex.position.x);
  95722. newPositionData.push(vertex.position.y);
  95723. newPositionData.push(vertex.position.z);
  95724. newNormalData.push(normalData[originalOffset * 3]);
  95725. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  95726. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  95727. if (uvs && uvs.length) {
  95728. newUVsData.push(uvs[(originalOffset * 2)]);
  95729. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  95730. }
  95731. else if (colorsData && colorsData.length) {
  95732. newColorsData.push(colorsData[(originalOffset * 4)]);
  95733. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  95734. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  95735. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  95736. }
  95737. ++vertexCount;
  95738. });
  95739. }
  95740. }
  95741. var startingIndex = this._reconstructedMesh.getTotalIndices();
  95742. var startingVertex = this._reconstructedMesh.getTotalVertices();
  95743. var submeshesArray = this._reconstructedMesh.subMeshes;
  95744. this._reconstructedMesh.subMeshes = [];
  95745. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  95746. var originalIndices = this._mesh.getIndices();
  95747. for (i = 0; i < newTriangles.length; ++i) {
  95748. t = newTriangles[i]; //now get the new referencing point for each vertex
  95749. [0, 1, 2].forEach(function (idx) {
  95750. var id = originalIndices[t.originalOffset + idx];
  95751. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  95752. if (offset < 0)
  95753. offset = 0;
  95754. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  95755. });
  95756. }
  95757. //overwriting the old vertex buffers and indices.
  95758. this._reconstructedMesh.setIndices(newIndicesArray);
  95759. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  95760. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  95761. if (newUVsData.length > 0)
  95762. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  95763. if (newColorsData.length > 0)
  95764. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  95765. //create submesh
  95766. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  95767. if (submeshIndex > 0) {
  95768. this._reconstructedMesh.subMeshes = [];
  95769. submeshesArray.forEach(function (submesh) {
  95770. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  95771. });
  95772. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  95773. }
  95774. };
  95775. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  95776. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  95777. this._reconstructedMesh.material = this._mesh.material;
  95778. this._reconstructedMesh.parent = this._mesh.parent;
  95779. this._reconstructedMesh.isVisible = false;
  95780. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  95781. };
  95782. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  95783. for (var i = 0; i < vertex1.triangleCount; ++i) {
  95784. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  95785. if (t.deleted)
  95786. continue;
  95787. var s = this.references[vertex1.triangleStart + i].vertexId;
  95788. var v1 = t.vertices[(s + 1) % 3];
  95789. var v2 = t.vertices[(s + 2) % 3];
  95790. if ((v1 === vertex2 || v2 === vertex2)) {
  95791. deletedArray[i] = true;
  95792. delTr.push(t);
  95793. continue;
  95794. }
  95795. var d1 = v1.position.subtract(point);
  95796. d1 = d1.normalize();
  95797. var d2 = v2.position.subtract(point);
  95798. d2 = d2.normalize();
  95799. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  95800. return true;
  95801. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  95802. deletedArray[i] = false;
  95803. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  95804. return true;
  95805. }
  95806. return false;
  95807. };
  95808. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  95809. var newDeleted = deletedTriangles;
  95810. for (var i = 0; i < vertex.triangleCount; ++i) {
  95811. var ref = this.references[vertex.triangleStart + i];
  95812. var t = this.triangles[ref.triangleId];
  95813. if (t.deleted)
  95814. continue;
  95815. if (deletedArray[i] && t.deletePending) {
  95816. t.deleted = true;
  95817. newDeleted++;
  95818. continue;
  95819. }
  95820. t.vertices[ref.vertexId] = origVertex;
  95821. t.isDirty = true;
  95822. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  95823. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  95824. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  95825. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95826. this.references.push(ref);
  95827. }
  95828. return newDeleted;
  95829. };
  95830. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  95831. for (var i = 0; i < this.vertices.length; ++i) {
  95832. var vCount = [];
  95833. var vId = [];
  95834. var v = this.vertices[i];
  95835. var j;
  95836. for (j = 0; j < v.triangleCount; ++j) {
  95837. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  95838. for (var ii = 0; ii < 3; ii++) {
  95839. var ofs = 0;
  95840. var vv = triangle.vertices[ii];
  95841. while (ofs < vCount.length) {
  95842. if (vId[ofs] === vv.id)
  95843. break;
  95844. ++ofs;
  95845. }
  95846. if (ofs === vCount.length) {
  95847. vCount.push(1);
  95848. vId.push(vv.id);
  95849. }
  95850. else {
  95851. vCount[ofs]++;
  95852. }
  95853. }
  95854. }
  95855. for (j = 0; j < vCount.length; ++j) {
  95856. if (vCount[j] === 1) {
  95857. this.vertices[vId[j]].isBorder = true;
  95858. }
  95859. else {
  95860. this.vertices[vId[j]].isBorder = false;
  95861. }
  95862. }
  95863. }
  95864. };
  95865. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  95866. if (identifyBorders === void 0) { identifyBorders = false; }
  95867. var i;
  95868. if (!identifyBorders) {
  95869. var newTrianglesVector = [];
  95870. for (i = 0; i < this.triangles.length; ++i) {
  95871. if (!this.triangles[i].deleted) {
  95872. newTrianglesVector.push(this.triangles[i]);
  95873. }
  95874. }
  95875. this.triangles = newTrianglesVector;
  95876. }
  95877. for (i = 0; i < this.vertices.length; ++i) {
  95878. this.vertices[i].triangleCount = 0;
  95879. this.vertices[i].triangleStart = 0;
  95880. }
  95881. var t;
  95882. var j;
  95883. var v;
  95884. for (i = 0; i < this.triangles.length; ++i) {
  95885. t = this.triangles[i];
  95886. for (j = 0; j < 3; ++j) {
  95887. v = t.vertices[j];
  95888. v.triangleCount++;
  95889. }
  95890. }
  95891. var tStart = 0;
  95892. for (i = 0; i < this.vertices.length; ++i) {
  95893. this.vertices[i].triangleStart = tStart;
  95894. tStart += this.vertices[i].triangleCount;
  95895. this.vertices[i].triangleCount = 0;
  95896. }
  95897. var newReferences = new Array(this.triangles.length * 3);
  95898. for (i = 0; i < this.triangles.length; ++i) {
  95899. t = this.triangles[i];
  95900. for (j = 0; j < 3; ++j) {
  95901. v = t.vertices[j];
  95902. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  95903. v.triangleCount++;
  95904. }
  95905. }
  95906. this.references = newReferences;
  95907. if (identifyBorders) {
  95908. this.identifyBorder();
  95909. }
  95910. };
  95911. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  95912. var x = point.x;
  95913. var y = point.y;
  95914. var z = point.z;
  95915. 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
  95916. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  95917. };
  95918. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  95919. var q = vertex1.q.add(vertex2.q);
  95920. var border = vertex1.isBorder && vertex2.isBorder;
  95921. var error = 0;
  95922. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  95923. if (qDet !== 0 && !border) {
  95924. if (!pointResult) {
  95925. pointResult = BABYLON.Vector3.Zero();
  95926. }
  95927. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  95928. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  95929. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  95930. error = this.vertexError(q, pointResult);
  95931. }
  95932. else {
  95933. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  95934. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  95935. var error1 = this.vertexError(q, vertex1.position);
  95936. var error2 = this.vertexError(q, vertex2.position);
  95937. var error3 = this.vertexError(q, p3);
  95938. error = Math.min(error1, error2, error3);
  95939. if (error === error1) {
  95940. if (pointResult) {
  95941. pointResult.copyFrom(vertex1.position);
  95942. }
  95943. }
  95944. else if (error === error2) {
  95945. if (pointResult) {
  95946. pointResult.copyFrom(vertex2.position);
  95947. }
  95948. }
  95949. else {
  95950. if (pointResult) {
  95951. pointResult.copyFrom(p3);
  95952. }
  95953. }
  95954. }
  95955. return error;
  95956. };
  95957. return QuadraticErrorSimplification;
  95958. }());
  95959. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  95960. })(BABYLON || (BABYLON = {}));
  95961. //# sourceMappingURL=babylon.meshSimplification.js.map
  95962. var BABYLON;
  95963. (function (BABYLON) {
  95964. var MeshLODLevel = /** @class */ (function () {
  95965. function MeshLODLevel(distance, mesh) {
  95966. this.distance = distance;
  95967. this.mesh = mesh;
  95968. }
  95969. return MeshLODLevel;
  95970. }());
  95971. BABYLON.MeshLODLevel = MeshLODLevel;
  95972. })(BABYLON || (BABYLON = {}));
  95973. //# sourceMappingURL=babylon.meshLODLevel.js.map
  95974. var BABYLON;
  95975. (function (BABYLON) {
  95976. /**
  95977. * Defines the root class used to create scene optimization to use with SceneOptimizer
  95978. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95979. */
  95980. var SceneOptimization = /** @class */ (function () {
  95981. /**
  95982. * Creates the SceneOptimization object
  95983. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95984. * @param desc defines the description associated with the optimization
  95985. */
  95986. function SceneOptimization(
  95987. /**
  95988. * Defines the priority of this optimization (0 by default which means first in the list)
  95989. */
  95990. priority) {
  95991. if (priority === void 0) { priority = 0; }
  95992. this.priority = priority;
  95993. }
  95994. /**
  95995. * Gets a string describing the action executed by the current optimization
  95996. * @returns description string
  95997. */
  95998. SceneOptimization.prototype.getDescription = function () {
  95999. return "";
  96000. };
  96001. /**
  96002. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96003. * @param scene defines the current scene where to apply this optimization
  96004. * @param optimizer defines the current optimizer
  96005. * @returns true if everything that can be done was applied
  96006. */
  96007. SceneOptimization.prototype.apply = function (scene, optimizer) {
  96008. return true;
  96009. };
  96010. ;
  96011. return SceneOptimization;
  96012. }());
  96013. BABYLON.SceneOptimization = SceneOptimization;
  96014. /**
  96015. * Defines an optimization used to reduce the size of render target textures
  96016. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96017. */
  96018. var TextureOptimization = /** @class */ (function (_super) {
  96019. __extends(TextureOptimization, _super);
  96020. /**
  96021. * Creates the TextureOptimization object
  96022. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96023. * @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
  96024. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  96025. */
  96026. function TextureOptimization(
  96027. /**
  96028. * Defines the priority of this optimization (0 by default which means first in the list)
  96029. */
  96030. priority,
  96031. /**
  96032. * 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
  96033. */
  96034. maximumSize,
  96035. /**
  96036. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  96037. */
  96038. step) {
  96039. if (priority === void 0) { priority = 0; }
  96040. if (maximumSize === void 0) { maximumSize = 1024; }
  96041. if (step === void 0) { step = 0.5; }
  96042. var _this = _super.call(this, priority) || this;
  96043. _this.priority = priority;
  96044. _this.maximumSize = maximumSize;
  96045. _this.step = step;
  96046. return _this;
  96047. }
  96048. /**
  96049. * Gets a string describing the action executed by the current optimization
  96050. * @returns description string
  96051. */
  96052. TextureOptimization.prototype.getDescription = function () {
  96053. return "Reducing render target texture size to " + this.maximumSize;
  96054. };
  96055. /**
  96056. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96057. * @param scene defines the current scene where to apply this optimization
  96058. * @param optimizer defines the current optimizer
  96059. * @returns true if everything that can be done was applied
  96060. */
  96061. TextureOptimization.prototype.apply = function (scene, optimizer) {
  96062. var allDone = true;
  96063. for (var index = 0; index < scene.textures.length; index++) {
  96064. var texture = scene.textures[index];
  96065. if (!texture.canRescale || texture.getContext) {
  96066. continue;
  96067. }
  96068. var currentSize = texture.getSize();
  96069. var maxDimension = Math.max(currentSize.width, currentSize.height);
  96070. if (maxDimension > this.maximumSize) {
  96071. texture.scale(this.step);
  96072. allDone = false;
  96073. }
  96074. }
  96075. return allDone;
  96076. };
  96077. return TextureOptimization;
  96078. }(SceneOptimization));
  96079. BABYLON.TextureOptimization = TextureOptimization;
  96080. /**
  96081. * Defines an optimization used to increase or decrease the rendering resolution
  96082. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96083. */
  96084. var HardwareScalingOptimization = /** @class */ (function (_super) {
  96085. __extends(HardwareScalingOptimization, _super);
  96086. /**
  96087. * Creates the HardwareScalingOptimization object
  96088. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96089. * @param maximumScale defines the maximum scale to use (2 by default)
  96090. * @param step defines the step to use between two passes (0.5 by default)
  96091. */
  96092. function HardwareScalingOptimization(
  96093. /**
  96094. * Defines the priority of this optimization (0 by default which means first in the list)
  96095. */
  96096. priority,
  96097. /**
  96098. * Defines the maximum scale to use (2 by default)
  96099. */
  96100. maximumScale,
  96101. /**
  96102. * Defines the step to use between two passes (0.5 by default)
  96103. */
  96104. step) {
  96105. if (priority === void 0) { priority = 0; }
  96106. if (maximumScale === void 0) { maximumScale = 2; }
  96107. if (step === void 0) { step = 0.25; }
  96108. var _this = _super.call(this, priority) || this;
  96109. _this.priority = priority;
  96110. _this.maximumScale = maximumScale;
  96111. _this.step = step;
  96112. _this._currentScale = -1;
  96113. _this._directionOffset = 1;
  96114. return _this;
  96115. }
  96116. /**
  96117. * Gets a string describing the action executed by the current optimization
  96118. * @return description string
  96119. */
  96120. HardwareScalingOptimization.prototype.getDescription = function () {
  96121. return "Setting hardware scaling level to " + this._currentScale;
  96122. };
  96123. /**
  96124. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96125. * @param scene defines the current scene where to apply this optimization
  96126. * @param optimizer defines the current optimizer
  96127. * @returns true if everything that can be done was applied
  96128. */
  96129. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  96130. if (this._currentScale === -1) {
  96131. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  96132. if (this._currentScale > this.maximumScale) {
  96133. this._directionOffset = -1;
  96134. }
  96135. }
  96136. this._currentScale += this._directionOffset * this.step;
  96137. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  96138. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  96139. };
  96140. ;
  96141. return HardwareScalingOptimization;
  96142. }(SceneOptimization));
  96143. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  96144. /**
  96145. * Defines an optimization used to remove shadows
  96146. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96147. */
  96148. var ShadowsOptimization = /** @class */ (function (_super) {
  96149. __extends(ShadowsOptimization, _super);
  96150. function ShadowsOptimization() {
  96151. return _super !== null && _super.apply(this, arguments) || this;
  96152. }
  96153. /**
  96154. * Gets a string describing the action executed by the current optimization
  96155. * @return description string
  96156. */
  96157. ShadowsOptimization.prototype.getDescription = function () {
  96158. return "Turning shadows on/off";
  96159. };
  96160. /**
  96161. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96162. * @param scene defines the current scene where to apply this optimization
  96163. * @param optimizer defines the current optimizer
  96164. * @returns true if everything that can be done was applied
  96165. */
  96166. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  96167. scene.shadowsEnabled = optimizer.isInImprovementMode;
  96168. return true;
  96169. };
  96170. ;
  96171. return ShadowsOptimization;
  96172. }(SceneOptimization));
  96173. BABYLON.ShadowsOptimization = ShadowsOptimization;
  96174. /**
  96175. * Defines an optimization used to turn post-processes off
  96176. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96177. */
  96178. var PostProcessesOptimization = /** @class */ (function (_super) {
  96179. __extends(PostProcessesOptimization, _super);
  96180. function PostProcessesOptimization() {
  96181. return _super !== null && _super.apply(this, arguments) || this;
  96182. }
  96183. /**
  96184. * Gets a string describing the action executed by the current optimization
  96185. * @return description string
  96186. */
  96187. PostProcessesOptimization.prototype.getDescription = function () {
  96188. return "Turning post-processes on/off";
  96189. };
  96190. /**
  96191. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96192. * @param scene defines the current scene where to apply this optimization
  96193. * @param optimizer defines the current optimizer
  96194. * @returns true if everything that can be done was applied
  96195. */
  96196. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  96197. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  96198. return true;
  96199. };
  96200. ;
  96201. return PostProcessesOptimization;
  96202. }(SceneOptimization));
  96203. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  96204. /**
  96205. * Defines an optimization used to turn lens flares off
  96206. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96207. */
  96208. var LensFlaresOptimization = /** @class */ (function (_super) {
  96209. __extends(LensFlaresOptimization, _super);
  96210. function LensFlaresOptimization() {
  96211. return _super !== null && _super.apply(this, arguments) || this;
  96212. }
  96213. /**
  96214. * Gets a string describing the action executed by the current optimization
  96215. * @return description string
  96216. */
  96217. LensFlaresOptimization.prototype.getDescription = function () {
  96218. return "Turning lens flares on/off";
  96219. };
  96220. /**
  96221. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96222. * @param scene defines the current scene where to apply this optimization
  96223. * @param optimizer defines the current optimizer
  96224. * @returns true if everything that can be done was applied
  96225. */
  96226. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  96227. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  96228. return true;
  96229. };
  96230. ;
  96231. return LensFlaresOptimization;
  96232. }(SceneOptimization));
  96233. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  96234. /**
  96235. * Defines an optimization based on user defined callback.
  96236. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96237. */
  96238. var CustomOptimization = /** @class */ (function (_super) {
  96239. __extends(CustomOptimization, _super);
  96240. function CustomOptimization() {
  96241. return _super !== null && _super.apply(this, arguments) || this;
  96242. }
  96243. /**
  96244. * Gets a string describing the action executed by the current optimization
  96245. * @returns description string
  96246. */
  96247. CustomOptimization.prototype.getDescription = function () {
  96248. if (this.onGetDescription) {
  96249. return this.onGetDescription();
  96250. }
  96251. return "Running user defined callback";
  96252. };
  96253. /**
  96254. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96255. * @param scene defines the current scene where to apply this optimization
  96256. * @param optimizer defines the current optimizer
  96257. * @returns true if everything that can be done was applied
  96258. */
  96259. CustomOptimization.prototype.apply = function (scene, optimizer) {
  96260. if (this.onApply) {
  96261. return this.onApply(scene, optimizer);
  96262. }
  96263. return true;
  96264. };
  96265. ;
  96266. return CustomOptimization;
  96267. }(SceneOptimization));
  96268. BABYLON.CustomOptimization = CustomOptimization;
  96269. /**
  96270. * Defines an optimization used to turn particles off
  96271. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96272. */
  96273. var ParticlesOptimization = /** @class */ (function (_super) {
  96274. __extends(ParticlesOptimization, _super);
  96275. function ParticlesOptimization() {
  96276. return _super !== null && _super.apply(this, arguments) || this;
  96277. }
  96278. /**
  96279. * Gets a string describing the action executed by the current optimization
  96280. * @return description string
  96281. */
  96282. ParticlesOptimization.prototype.getDescription = function () {
  96283. return "Turning particles on/off";
  96284. };
  96285. /**
  96286. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96287. * @param scene defines the current scene where to apply this optimization
  96288. * @param optimizer defines the current optimizer
  96289. * @returns true if everything that can be done was applied
  96290. */
  96291. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  96292. scene.particlesEnabled = optimizer.isInImprovementMode;
  96293. return true;
  96294. };
  96295. ;
  96296. return ParticlesOptimization;
  96297. }(SceneOptimization));
  96298. BABYLON.ParticlesOptimization = ParticlesOptimization;
  96299. /**
  96300. * Defines an optimization used to turn render targets off
  96301. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96302. */
  96303. var RenderTargetsOptimization = /** @class */ (function (_super) {
  96304. __extends(RenderTargetsOptimization, _super);
  96305. function RenderTargetsOptimization() {
  96306. return _super !== null && _super.apply(this, arguments) || this;
  96307. }
  96308. /**
  96309. * Gets a string describing the action executed by the current optimization
  96310. * @return description string
  96311. */
  96312. RenderTargetsOptimization.prototype.getDescription = function () {
  96313. return "Turning render targets off";
  96314. };
  96315. /**
  96316. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96317. * @param scene defines the current scene where to apply this optimization
  96318. * @param optimizer defines the current optimizer
  96319. * @returns true if everything that can be done was applied
  96320. */
  96321. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  96322. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  96323. return true;
  96324. };
  96325. ;
  96326. return RenderTargetsOptimization;
  96327. }(SceneOptimization));
  96328. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  96329. /**
  96330. * Defines an optimization used to merge meshes with compatible materials
  96331. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96332. */
  96333. var MergeMeshesOptimization = /** @class */ (function (_super) {
  96334. __extends(MergeMeshesOptimization, _super);
  96335. function MergeMeshesOptimization() {
  96336. var _this = _super !== null && _super.apply(this, arguments) || this;
  96337. _this._canBeMerged = function (abstractMesh) {
  96338. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  96339. return false;
  96340. }
  96341. var mesh = abstractMesh;
  96342. if (mesh.isDisposed()) {
  96343. return false;
  96344. }
  96345. if (!mesh.isVisible || !mesh.isEnabled()) {
  96346. return false;
  96347. }
  96348. if (mesh.instances.length > 0) {
  96349. return false;
  96350. }
  96351. if (mesh.skeleton || mesh.hasLODLevels) {
  96352. return false;
  96353. }
  96354. return true;
  96355. };
  96356. return _this;
  96357. }
  96358. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  96359. /**
  96360. * Gets or sets a boolean which defines if optimization octree has to be updated
  96361. */
  96362. get: function () {
  96363. return MergeMeshesOptimization._UpdateSelectionTree;
  96364. },
  96365. /**
  96366. * Gets or sets a boolean which defines if optimization octree has to be updated
  96367. */
  96368. set: function (value) {
  96369. MergeMeshesOptimization._UpdateSelectionTree = value;
  96370. },
  96371. enumerable: true,
  96372. configurable: true
  96373. });
  96374. /**
  96375. * Gets a string describing the action executed by the current optimization
  96376. * @return description string
  96377. */
  96378. MergeMeshesOptimization.prototype.getDescription = function () {
  96379. return "Merging similar meshes together";
  96380. };
  96381. /**
  96382. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96383. * @param scene defines the current scene where to apply this optimization
  96384. * @param optimizer defines the current optimizer
  96385. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  96386. * @returns true if everything that can be done was applied
  96387. */
  96388. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  96389. var globalPool = scene.meshes.slice(0);
  96390. var globalLength = globalPool.length;
  96391. for (var index = 0; index < globalLength; index++) {
  96392. var currentPool = new Array();
  96393. var current = globalPool[index];
  96394. // Checks
  96395. if (!this._canBeMerged(current)) {
  96396. continue;
  96397. }
  96398. currentPool.push(current);
  96399. // Find compatible meshes
  96400. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  96401. var otherMesh = globalPool[subIndex];
  96402. if (!this._canBeMerged(otherMesh)) {
  96403. continue;
  96404. }
  96405. if (otherMesh.material !== current.material) {
  96406. continue;
  96407. }
  96408. if (otherMesh.checkCollisions !== current.checkCollisions) {
  96409. continue;
  96410. }
  96411. currentPool.push(otherMesh);
  96412. globalLength--;
  96413. globalPool.splice(subIndex, 1);
  96414. subIndex--;
  96415. }
  96416. if (currentPool.length < 2) {
  96417. continue;
  96418. }
  96419. // Merge meshes
  96420. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  96421. }
  96422. if (updateSelectionTree != undefined) {
  96423. if (updateSelectionTree) {
  96424. scene.createOrUpdateSelectionOctree();
  96425. }
  96426. }
  96427. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  96428. scene.createOrUpdateSelectionOctree();
  96429. }
  96430. return true;
  96431. };
  96432. ;
  96433. MergeMeshesOptimization._UpdateSelectionTree = false;
  96434. return MergeMeshesOptimization;
  96435. }(SceneOptimization));
  96436. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  96437. /**
  96438. * Defines a list of options used by SceneOptimizer
  96439. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96440. */
  96441. var SceneOptimizerOptions = /** @class */ (function () {
  96442. /**
  96443. * Creates a new list of options used by SceneOptimizer
  96444. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  96445. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  96446. */
  96447. function SceneOptimizerOptions(
  96448. /**
  96449. * Defines the target frame rate to reach (60 by default)
  96450. */
  96451. targetFrameRate,
  96452. /**
  96453. * Defines the interval between two checkes (2000ms by default)
  96454. */
  96455. trackerDuration) {
  96456. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  96457. if (trackerDuration === void 0) { trackerDuration = 2000; }
  96458. this.targetFrameRate = targetFrameRate;
  96459. this.trackerDuration = trackerDuration;
  96460. /**
  96461. * Gets the list of optimizations to apply
  96462. */
  96463. this.optimizations = new Array();
  96464. }
  96465. /**
  96466. * Add a new optimization
  96467. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  96468. * @returns the current SceneOptimizerOptions
  96469. */
  96470. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  96471. this.optimizations.push(optimization);
  96472. return this;
  96473. };
  96474. /**
  96475. * Add a new custom optimization
  96476. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  96477. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  96478. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96479. * @returns the current SceneOptimizerOptions
  96480. */
  96481. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  96482. if (priority === void 0) { priority = 0; }
  96483. var optimization = new CustomOptimization(priority);
  96484. optimization.onApply = onApply;
  96485. optimization.onGetDescription = onGetDescription;
  96486. this.optimizations.push(optimization);
  96487. return this;
  96488. };
  96489. /**
  96490. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  96491. * @param targetFrameRate defines the target frame rate (60 by default)
  96492. * @returns a SceneOptimizerOptions object
  96493. */
  96494. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  96495. var result = new SceneOptimizerOptions(targetFrameRate);
  96496. var priority = 0;
  96497. result.addOptimization(new MergeMeshesOptimization(priority));
  96498. result.addOptimization(new ShadowsOptimization(priority));
  96499. result.addOptimization(new LensFlaresOptimization(priority));
  96500. // Next priority
  96501. priority++;
  96502. result.addOptimization(new PostProcessesOptimization(priority));
  96503. result.addOptimization(new ParticlesOptimization(priority));
  96504. // Next priority
  96505. priority++;
  96506. result.addOptimization(new TextureOptimization(priority, 1024));
  96507. return result;
  96508. };
  96509. /**
  96510. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  96511. * @param targetFrameRate defines the target frame rate (60 by default)
  96512. * @returns a SceneOptimizerOptions object
  96513. */
  96514. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  96515. var result = new SceneOptimizerOptions(targetFrameRate);
  96516. var priority = 0;
  96517. result.addOptimization(new MergeMeshesOptimization(priority));
  96518. result.addOptimization(new ShadowsOptimization(priority));
  96519. result.addOptimization(new LensFlaresOptimization(priority));
  96520. // Next priority
  96521. priority++;
  96522. result.addOptimization(new PostProcessesOptimization(priority));
  96523. result.addOptimization(new ParticlesOptimization(priority));
  96524. // Next priority
  96525. priority++;
  96526. result.addOptimization(new TextureOptimization(priority, 512));
  96527. // Next priority
  96528. priority++;
  96529. result.addOptimization(new RenderTargetsOptimization(priority));
  96530. // Next priority
  96531. priority++;
  96532. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  96533. return result;
  96534. };
  96535. /**
  96536. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  96537. * @param targetFrameRate defines the target frame rate (60 by default)
  96538. * @returns a SceneOptimizerOptions object
  96539. */
  96540. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  96541. var result = new SceneOptimizerOptions(targetFrameRate);
  96542. var priority = 0;
  96543. result.addOptimization(new MergeMeshesOptimization(priority));
  96544. result.addOptimization(new ShadowsOptimization(priority));
  96545. result.addOptimization(new LensFlaresOptimization(priority));
  96546. // Next priority
  96547. priority++;
  96548. result.addOptimization(new PostProcessesOptimization(priority));
  96549. result.addOptimization(new ParticlesOptimization(priority));
  96550. // Next priority
  96551. priority++;
  96552. result.addOptimization(new TextureOptimization(priority, 256));
  96553. // Next priority
  96554. priority++;
  96555. result.addOptimization(new RenderTargetsOptimization(priority));
  96556. // Next priority
  96557. priority++;
  96558. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  96559. return result;
  96560. };
  96561. return SceneOptimizerOptions;
  96562. }());
  96563. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  96564. /**
  96565. * Class used to run optimizations in order to reach a target frame rate
  96566. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96567. */
  96568. var SceneOptimizer = /** @class */ (function () {
  96569. /**
  96570. * Creates a new SceneOptimizer
  96571. * @param scene defines the scene to work on
  96572. * @param options defines the options to use with the SceneOptimizer
  96573. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  96574. * @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)
  96575. */
  96576. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  96577. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  96578. if (improvementMode === void 0) { improvementMode = false; }
  96579. var _this = this;
  96580. this._isRunning = false;
  96581. this._currentPriorityLevel = 0;
  96582. this._targetFrameRate = 60;
  96583. this._trackerDuration = 2000;
  96584. this._currentFrameRate = 0;
  96585. this._improvementMode = false;
  96586. /**
  96587. * Defines an observable called when the optimizer reaches the target frame rate
  96588. */
  96589. this.onSuccessObservable = new BABYLON.Observable();
  96590. /**
  96591. * Defines an observable called when the optimizer enables an optimization
  96592. */
  96593. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  96594. /**
  96595. * Defines an observable called when the optimizer is not able to reach the target frame rate
  96596. */
  96597. this.onFailureObservable = new BABYLON.Observable();
  96598. if (!options) {
  96599. this._options = new SceneOptimizerOptions();
  96600. }
  96601. else {
  96602. this._options = options;
  96603. }
  96604. if (this._options.targetFrameRate) {
  96605. this._targetFrameRate = this._options.targetFrameRate;
  96606. }
  96607. if (this._options.trackerDuration) {
  96608. this._trackerDuration = this._options.trackerDuration;
  96609. }
  96610. if (autoGeneratePriorities) {
  96611. var priority = 0;
  96612. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  96613. var optim = _a[_i];
  96614. optim.priority = priority++;
  96615. }
  96616. }
  96617. this._improvementMode = improvementMode;
  96618. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96619. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  96620. _this._sceneDisposeObserver = null;
  96621. _this.dispose();
  96622. });
  96623. }
  96624. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  96625. /**
  96626. * Gets a boolean indicating if the optimizer is in improvement mode
  96627. */
  96628. get: function () {
  96629. return this._improvementMode;
  96630. },
  96631. enumerable: true,
  96632. configurable: true
  96633. });
  96634. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  96635. /**
  96636. * Gets the current priority level (0 at start)
  96637. */
  96638. get: function () {
  96639. return this._currentPriorityLevel;
  96640. },
  96641. enumerable: true,
  96642. configurable: true
  96643. });
  96644. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  96645. /**
  96646. * Gets the current frame rate checked by the SceneOptimizer
  96647. */
  96648. get: function () {
  96649. return this._currentFrameRate;
  96650. },
  96651. enumerable: true,
  96652. configurable: true
  96653. });
  96654. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  96655. /**
  96656. * Gets or sets the current target frame rate (60 by default)
  96657. */
  96658. get: function () {
  96659. return this._targetFrameRate;
  96660. },
  96661. /**
  96662. * Gets or sets the current target frame rate (60 by default)
  96663. */
  96664. set: function (value) {
  96665. this._targetFrameRate = value;
  96666. },
  96667. enumerable: true,
  96668. configurable: true
  96669. });
  96670. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  96671. /**
  96672. * Gets or sets the current interval between two checks (every 2000ms by default)
  96673. */
  96674. get: function () {
  96675. return this._trackerDuration;
  96676. },
  96677. /**
  96678. * Gets or sets the current interval between two checks (every 2000ms by default)
  96679. */
  96680. set: function (value) {
  96681. this._trackerDuration = value;
  96682. },
  96683. enumerable: true,
  96684. configurable: true
  96685. });
  96686. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  96687. /**
  96688. * Gets the list of active optimizations
  96689. */
  96690. get: function () {
  96691. return this._options.optimizations;
  96692. },
  96693. enumerable: true,
  96694. configurable: true
  96695. });
  96696. /**
  96697. * Stops the current optimizer
  96698. */
  96699. SceneOptimizer.prototype.stop = function () {
  96700. this._isRunning = false;
  96701. };
  96702. /**
  96703. * Reset the optimizer to initial step (current priority level = 0)
  96704. */
  96705. SceneOptimizer.prototype.reset = function () {
  96706. this._currentPriorityLevel = 0;
  96707. };
  96708. /**
  96709. * Start the optimizer. By default it will try to reach a specific framerate
  96710. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  96711. */
  96712. SceneOptimizer.prototype.start = function () {
  96713. var _this = this;
  96714. if (this._isRunning) {
  96715. return;
  96716. }
  96717. this._isRunning = true;
  96718. // Let's wait for the scene to be ready before running our check
  96719. this._scene.executeWhenReady(function () {
  96720. setTimeout(function () {
  96721. _this._checkCurrentState();
  96722. }, _this._trackerDuration);
  96723. });
  96724. };
  96725. SceneOptimizer.prototype._checkCurrentState = function () {
  96726. var _this = this;
  96727. if (!this._isRunning) {
  96728. return;
  96729. }
  96730. var scene = this._scene;
  96731. var options = this._options;
  96732. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  96733. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  96734. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  96735. this._isRunning = false;
  96736. this.onSuccessObservable.notifyObservers(this);
  96737. return;
  96738. }
  96739. // Apply current level of optimizations
  96740. var allDone = true;
  96741. var noOptimizationApplied = true;
  96742. for (var index = 0; index < options.optimizations.length; index++) {
  96743. var optimization = options.optimizations[index];
  96744. if (optimization.priority === this._currentPriorityLevel) {
  96745. noOptimizationApplied = false;
  96746. allDone = allDone && optimization.apply(scene, this);
  96747. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  96748. }
  96749. }
  96750. // If no optimization was applied, this is a failure :(
  96751. if (noOptimizationApplied) {
  96752. this._isRunning = false;
  96753. this.onFailureObservable.notifyObservers(this);
  96754. return;
  96755. }
  96756. // If all optimizations were done, move to next level
  96757. if (allDone) {
  96758. this._currentPriorityLevel++;
  96759. }
  96760. // Let's the system running for a specific amount of time before checking FPS
  96761. scene.executeWhenReady(function () {
  96762. setTimeout(function () {
  96763. _this._checkCurrentState();
  96764. }, _this._trackerDuration);
  96765. });
  96766. };
  96767. /**
  96768. * Release all resources
  96769. */
  96770. SceneOptimizer.prototype.dispose = function () {
  96771. this.stop();
  96772. this.onSuccessObservable.clear();
  96773. this.onFailureObservable.clear();
  96774. this.onNewOptimizationAppliedObservable.clear();
  96775. if (this._sceneDisposeObserver) {
  96776. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96777. }
  96778. };
  96779. /**
  96780. * Helper function to create a SceneOptimizer with one single line of code
  96781. * @param scene defines the scene to work on
  96782. * @param options defines the options to use with the SceneOptimizer
  96783. * @param onSuccess defines a callback to call on success
  96784. * @param onFailure defines a callback to call on failure
  96785. * @returns the new SceneOptimizer object
  96786. */
  96787. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  96788. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  96789. if (onSuccess) {
  96790. optimizer.onSuccessObservable.add(function () {
  96791. onSuccess();
  96792. });
  96793. }
  96794. if (onFailure) {
  96795. optimizer.onFailureObservable.add(function () {
  96796. onFailure();
  96797. });
  96798. }
  96799. optimizer.start();
  96800. return optimizer;
  96801. };
  96802. return SceneOptimizer;
  96803. }());
  96804. BABYLON.SceneOptimizer = SceneOptimizer;
  96805. })(BABYLON || (BABYLON = {}));
  96806. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  96807. var BABYLON;
  96808. (function (BABYLON) {
  96809. var OutlineRenderer = /** @class */ (function () {
  96810. function OutlineRenderer(scene) {
  96811. this.zOffset = 1;
  96812. this._scene = scene;
  96813. }
  96814. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  96815. var _this = this;
  96816. if (useOverlay === void 0) { useOverlay = false; }
  96817. var scene = this._scene;
  96818. var engine = this._scene.getEngine();
  96819. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96820. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  96821. return;
  96822. }
  96823. var mesh = subMesh.getRenderingMesh();
  96824. var material = subMesh.getMaterial();
  96825. if (!material || !scene.activeCamera) {
  96826. return;
  96827. }
  96828. engine.enableEffect(this._effect);
  96829. // Logarithmic depth
  96830. if (material.useLogarithmicDepth) {
  96831. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  96832. }
  96833. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  96834. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  96835. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  96836. // Bones
  96837. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96838. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96839. }
  96840. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  96841. // Alpha test
  96842. if (material && material.needAlphaTesting()) {
  96843. var alphaTexture = material.getAlphaTestTexture();
  96844. if (alphaTexture) {
  96845. this._effect.setTexture("diffuseSampler", alphaTexture);
  96846. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  96847. }
  96848. }
  96849. engine.setZOffset(-this.zOffset);
  96850. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  96851. engine.setZOffset(0);
  96852. };
  96853. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  96854. var defines = [];
  96855. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  96856. var mesh = subMesh.getMesh();
  96857. var material = subMesh.getMaterial();
  96858. if (material) {
  96859. // Alpha test
  96860. if (material.needAlphaTesting()) {
  96861. defines.push("#define ALPHATEST");
  96862. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96863. attribs.push(BABYLON.VertexBuffer.UVKind);
  96864. defines.push("#define UV1");
  96865. }
  96866. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  96867. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96868. defines.push("#define UV2");
  96869. }
  96870. }
  96871. //Logarithmic depth
  96872. if (material.useLogarithmicDepth) {
  96873. defines.push("#define LOGARITHMICDEPTH");
  96874. }
  96875. }
  96876. // Bones
  96877. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96878. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96879. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96880. if (mesh.numBoneInfluencers > 4) {
  96881. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96882. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96883. }
  96884. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96885. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  96886. }
  96887. else {
  96888. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96889. }
  96890. // Instances
  96891. if (useInstances) {
  96892. defines.push("#define INSTANCES");
  96893. attribs.push("world0");
  96894. attribs.push("world1");
  96895. attribs.push("world2");
  96896. attribs.push("world3");
  96897. }
  96898. // Get correct effect
  96899. var join = defines.join("\n");
  96900. if (this._cachedDefines !== join) {
  96901. this._cachedDefines = join;
  96902. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  96903. }
  96904. return this._effect.isReady();
  96905. };
  96906. return OutlineRenderer;
  96907. }());
  96908. BABYLON.OutlineRenderer = OutlineRenderer;
  96909. })(BABYLON || (BABYLON = {}));
  96910. //# sourceMappingURL=babylon.outlineRenderer.js.map
  96911. var BABYLON;
  96912. (function (BABYLON) {
  96913. var FaceAdjacencies = /** @class */ (function () {
  96914. function FaceAdjacencies() {
  96915. this.edges = new Array();
  96916. this.edgesConnectedCount = 0;
  96917. }
  96918. return FaceAdjacencies;
  96919. }());
  96920. var EdgesRenderer = /** @class */ (function () {
  96921. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  96922. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  96923. if (epsilon === void 0) { epsilon = 0.95; }
  96924. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  96925. this.edgesWidthScalerForOrthographic = 1000.0;
  96926. this.edgesWidthScalerForPerspective = 50.0;
  96927. this._linesPositions = new Array();
  96928. this._linesNormals = new Array();
  96929. this._linesIndices = new Array();
  96930. this._buffers = {};
  96931. this._checkVerticesInsteadOfIndices = false;
  96932. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  96933. this.isEnabled = true;
  96934. this._source = source;
  96935. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  96936. this._epsilon = epsilon;
  96937. this._prepareRessources();
  96938. this._generateEdgesLines();
  96939. }
  96940. EdgesRenderer.prototype._prepareRessources = function () {
  96941. if (this._lineShader) {
  96942. return;
  96943. }
  96944. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  96945. attributes: ["position", "normal"],
  96946. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  96947. });
  96948. this._lineShader.disableDepthWrite = true;
  96949. this._lineShader.backFaceCulling = false;
  96950. };
  96951. EdgesRenderer.prototype._rebuild = function () {
  96952. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96953. if (buffer) {
  96954. buffer._rebuild();
  96955. }
  96956. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96957. if (buffer) {
  96958. buffer._rebuild();
  96959. }
  96960. var scene = this._source.getScene();
  96961. var engine = scene.getEngine();
  96962. this._ib = engine.createIndexBuffer(this._linesIndices);
  96963. };
  96964. EdgesRenderer.prototype.dispose = function () {
  96965. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96966. if (buffer) {
  96967. buffer.dispose();
  96968. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  96969. }
  96970. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96971. if (buffer) {
  96972. buffer.dispose();
  96973. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  96974. }
  96975. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  96976. this._lineShader.dispose();
  96977. };
  96978. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  96979. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  96980. return 0;
  96981. }
  96982. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  96983. return 1;
  96984. }
  96985. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  96986. return 2;
  96987. }
  96988. return -1;
  96989. };
  96990. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96991. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96992. return 0;
  96993. }
  96994. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96995. return 1;
  96996. }
  96997. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96998. return 2;
  96999. }
  97000. return -1;
  97001. };
  97002. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  97003. var needToCreateLine;
  97004. if (edge === undefined) {
  97005. needToCreateLine = true;
  97006. }
  97007. else {
  97008. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  97009. needToCreateLine = dotProduct < this._epsilon;
  97010. }
  97011. if (needToCreateLine) {
  97012. var offset = this._linesPositions.length / 3;
  97013. var normal = p0.subtract(p1);
  97014. normal.normalize();
  97015. // Positions
  97016. this._linesPositions.push(p0.x);
  97017. this._linesPositions.push(p0.y);
  97018. this._linesPositions.push(p0.z);
  97019. this._linesPositions.push(p0.x);
  97020. this._linesPositions.push(p0.y);
  97021. this._linesPositions.push(p0.z);
  97022. this._linesPositions.push(p1.x);
  97023. this._linesPositions.push(p1.y);
  97024. this._linesPositions.push(p1.z);
  97025. this._linesPositions.push(p1.x);
  97026. this._linesPositions.push(p1.y);
  97027. this._linesPositions.push(p1.z);
  97028. // Normals
  97029. this._linesNormals.push(p1.x);
  97030. this._linesNormals.push(p1.y);
  97031. this._linesNormals.push(p1.z);
  97032. this._linesNormals.push(-1);
  97033. this._linesNormals.push(p1.x);
  97034. this._linesNormals.push(p1.y);
  97035. this._linesNormals.push(p1.z);
  97036. this._linesNormals.push(1);
  97037. this._linesNormals.push(p0.x);
  97038. this._linesNormals.push(p0.y);
  97039. this._linesNormals.push(p0.z);
  97040. this._linesNormals.push(-1);
  97041. this._linesNormals.push(p0.x);
  97042. this._linesNormals.push(p0.y);
  97043. this._linesNormals.push(p0.z);
  97044. this._linesNormals.push(1);
  97045. // Indices
  97046. this._linesIndices.push(offset);
  97047. this._linesIndices.push(offset + 1);
  97048. this._linesIndices.push(offset + 2);
  97049. this._linesIndices.push(offset);
  97050. this._linesIndices.push(offset + 2);
  97051. this._linesIndices.push(offset + 3);
  97052. }
  97053. };
  97054. EdgesRenderer.prototype._generateEdgesLines = function () {
  97055. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  97056. var indices = this._source.getIndices();
  97057. if (!indices || !positions) {
  97058. return;
  97059. }
  97060. // First let's find adjacencies
  97061. var adjacencies = new Array();
  97062. var faceNormals = new Array();
  97063. var index;
  97064. var faceAdjacencies;
  97065. // Prepare faces
  97066. for (index = 0; index < indices.length; index += 3) {
  97067. faceAdjacencies = new FaceAdjacencies();
  97068. var p0Index = indices[index];
  97069. var p1Index = indices[index + 1];
  97070. var p2Index = indices[index + 2];
  97071. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  97072. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  97073. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  97074. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  97075. faceNormal.normalize();
  97076. faceNormals.push(faceNormal);
  97077. adjacencies.push(faceAdjacencies);
  97078. }
  97079. // Scan
  97080. for (index = 0; index < adjacencies.length; index++) {
  97081. faceAdjacencies = adjacencies[index];
  97082. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  97083. var otherFaceAdjacencies = adjacencies[otherIndex];
  97084. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  97085. break;
  97086. }
  97087. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  97088. continue;
  97089. }
  97090. var otherP0 = indices[otherIndex * 3];
  97091. var otherP1 = indices[otherIndex * 3 + 1];
  97092. var otherP2 = indices[otherIndex * 3 + 2];
  97093. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  97094. var otherEdgeIndex = 0;
  97095. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  97096. continue;
  97097. }
  97098. switch (edgeIndex) {
  97099. case 0:
  97100. if (this._checkVerticesInsteadOfIndices) {
  97101. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97102. }
  97103. else {
  97104. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  97105. }
  97106. break;
  97107. case 1:
  97108. if (this._checkVerticesInsteadOfIndices) {
  97109. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97110. }
  97111. else {
  97112. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  97113. }
  97114. break;
  97115. case 2:
  97116. if (this._checkVerticesInsteadOfIndices) {
  97117. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97118. }
  97119. else {
  97120. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  97121. }
  97122. break;
  97123. }
  97124. if (otherEdgeIndex === -1) {
  97125. continue;
  97126. }
  97127. faceAdjacencies.edges[edgeIndex] = otherIndex;
  97128. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  97129. faceAdjacencies.edgesConnectedCount++;
  97130. otherFaceAdjacencies.edgesConnectedCount++;
  97131. if (faceAdjacencies.edgesConnectedCount === 3) {
  97132. break;
  97133. }
  97134. }
  97135. }
  97136. }
  97137. // Create lines
  97138. for (index = 0; index < adjacencies.length; index++) {
  97139. // 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
  97140. var current = adjacencies[index];
  97141. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  97142. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  97143. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  97144. }
  97145. // Merge into a single mesh
  97146. var engine = this._source.getScene().getEngine();
  97147. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  97148. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  97149. this._ib = engine.createIndexBuffer(this._linesIndices);
  97150. this._indicesCount = this._linesIndices.length;
  97151. };
  97152. EdgesRenderer.prototype.render = function () {
  97153. var scene = this._source.getScene();
  97154. if (!this._lineShader.isReady() || !scene.activeCamera) {
  97155. return;
  97156. }
  97157. var engine = scene.getEngine();
  97158. this._lineShader._preBind();
  97159. // VBOs
  97160. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  97161. scene.resetCachedMaterial();
  97162. this._lineShader.setColor4("color", this._source.edgesColor);
  97163. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  97164. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  97165. }
  97166. else {
  97167. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  97168. }
  97169. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  97170. this._lineShader.bind(this._source.getWorldMatrix());
  97171. // Draw order
  97172. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  97173. this._lineShader.unbind();
  97174. engine.setDepthWrite(true);
  97175. };
  97176. return EdgesRenderer;
  97177. }());
  97178. BABYLON.EdgesRenderer = EdgesRenderer;
  97179. })(BABYLON || (BABYLON = {}));
  97180. //# sourceMappingURL=babylon.edgesRenderer.js.map
  97181. var BABYLON;
  97182. (function (BABYLON) {
  97183. // Adds the parser to the scene parsers.
  97184. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  97185. if (parsedData.effectLayers) {
  97186. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  97187. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  97188. container.effectLayers.push(effectLayer);
  97189. }
  97190. }
  97191. });
  97192. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  97193. var index = this.effectLayers.indexOf(toRemove);
  97194. if (index !== -1) {
  97195. this.effectLayers.splice(index, 1);
  97196. }
  97197. return index;
  97198. };
  97199. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  97200. this.effectLayers.push(newEffectLayer);
  97201. };
  97202. /**
  97203. * Defines the layer scene component responsible to manage any effect layers
  97204. * in a given scene.
  97205. */
  97206. var EffectLayerSceneComponent = /** @class */ (function () {
  97207. /**
  97208. * Creates a new instance of the component for the given scene
  97209. * @param scene Defines the scene to register the component in
  97210. */
  97211. function EffectLayerSceneComponent(scene) {
  97212. /**
  97213. * The component name helpfull to identify the component in the list of scene components.
  97214. */
  97215. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  97216. this._renderEffects = false;
  97217. this._needStencil = false;
  97218. this._previousStencilState = false;
  97219. this.scene = scene;
  97220. this._engine = scene.getEngine();
  97221. scene.effectLayers = new Array();
  97222. }
  97223. /**
  97224. * Registers the component in a given scene
  97225. */
  97226. EffectLayerSceneComponent.prototype.register = function () {
  97227. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  97228. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  97229. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  97230. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  97231. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  97232. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  97233. };
  97234. /**
  97235. * Rebuilds the elements related to this component in case of
  97236. * context lost for instance.
  97237. */
  97238. EffectLayerSceneComponent.prototype.rebuild = function () {
  97239. var layers = this.scene.effectLayers;
  97240. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  97241. var effectLayer = layers_1[_i];
  97242. effectLayer._rebuild();
  97243. }
  97244. };
  97245. /**
  97246. * Serializes the component data to the specified json object
  97247. * @param serializationObject The object to serialize to
  97248. */
  97249. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  97250. // Effect layers
  97251. serializationObject.effectLayers = [];
  97252. var layers = this.scene.effectLayers;
  97253. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  97254. var effectLayer = layers_2[_i];
  97255. if (effectLayer.serialize) {
  97256. serializationObject.effectLayers.push(effectLayer.serialize());
  97257. }
  97258. }
  97259. };
  97260. /**
  97261. * Adds all the element from the container to the scene
  97262. * @param container the container holding the elements
  97263. */
  97264. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  97265. var _this = this;
  97266. if (!container.effectLayers) {
  97267. return;
  97268. }
  97269. container.effectLayers.forEach(function (o) {
  97270. _this.scene.addEffectLayer(o);
  97271. });
  97272. };
  97273. /**
  97274. * Removes all the elements in the container from the scene
  97275. * @param container contains the elements to remove
  97276. */
  97277. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  97278. var _this = this;
  97279. if (!container.effectLayers) {
  97280. return;
  97281. }
  97282. container.effectLayers.forEach(function (o) {
  97283. _this.scene.removeEffectLayer(o);
  97284. });
  97285. };
  97286. /**
  97287. * Disposes the component and the associated ressources.
  97288. */
  97289. EffectLayerSceneComponent.prototype.dispose = function () {
  97290. var layers = this.scene.effectLayers;
  97291. while (layers.length) {
  97292. layers[0].dispose();
  97293. }
  97294. };
  97295. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  97296. var layers = this.scene.effectLayers;
  97297. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  97298. var layer = layers_3[_i];
  97299. if (!layer.hasMesh(mesh)) {
  97300. continue;
  97301. }
  97302. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  97303. var subMesh = _b[_a];
  97304. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  97305. return false;
  97306. }
  97307. }
  97308. }
  97309. return true;
  97310. };
  97311. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  97312. this._renderEffects = false;
  97313. this._needStencil = false;
  97314. var layers = this.scene.effectLayers;
  97315. if (layers && layers.length > 0) {
  97316. this._previousStencilState = this._engine.getStencilBuffer();
  97317. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  97318. var effectLayer = layers_4[_i];
  97319. if (effectLayer.shouldRender() &&
  97320. (!effectLayer.camera ||
  97321. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  97322. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  97323. this._renderEffects = true;
  97324. this._needStencil = this._needStencil || effectLayer.needStencil();
  97325. var renderTarget = effectLayer._mainTexture;
  97326. if (renderTarget._shouldRender()) {
  97327. this.scene.incrementRenderId();
  97328. renderTarget.render(false, false);
  97329. }
  97330. }
  97331. }
  97332. this.scene.incrementRenderId();
  97333. }
  97334. };
  97335. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  97336. // Activate effect Layer stencil
  97337. if (this._needStencil) {
  97338. this._engine.setStencilBuffer(true);
  97339. }
  97340. };
  97341. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  97342. // Restore effect Layer stencil
  97343. if (this._needStencil) {
  97344. this._engine.setStencilBuffer(this._previousStencilState);
  97345. }
  97346. };
  97347. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  97348. if (this._renderEffects) {
  97349. this._engine.setDepthBuffer(false);
  97350. var layers = this.scene.effectLayers;
  97351. for (var i = 0; i < layers.length; i++) {
  97352. var effectLayer = layers[i];
  97353. if (effectLayer.renderingGroupId === renderingGroupId) {
  97354. if (effectLayer.shouldRender()) {
  97355. effectLayer.render();
  97356. }
  97357. }
  97358. }
  97359. this._engine.setDepthBuffer(true);
  97360. }
  97361. };
  97362. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  97363. if (this._renderEffects) {
  97364. this._draw(-1);
  97365. }
  97366. };
  97367. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  97368. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  97369. this._draw(index);
  97370. }
  97371. };
  97372. return EffectLayerSceneComponent;
  97373. }());
  97374. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  97375. })(BABYLON || (BABYLON = {}));
  97376. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  97377. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97378. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97379. s = arguments[i];
  97380. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97381. t[p] = s[p];
  97382. }
  97383. return t;
  97384. };
  97385. var BABYLON;
  97386. (function (BABYLON) {
  97387. /**
  97388. * The effect layer Helps adding post process effect blended with the main pass.
  97389. *
  97390. * This can be for instance use to generate glow or higlight effects on the scene.
  97391. *
  97392. * The effect layer class can not be used directly and is intented to inherited from to be
  97393. * customized per effects.
  97394. */
  97395. var EffectLayer = /** @class */ (function () {
  97396. /**
  97397. * Instantiates a new effect Layer and references it in the scene.
  97398. * @param name The name of the layer
  97399. * @param scene The scene to use the layer in
  97400. */
  97401. function EffectLayer(
  97402. /** The Friendly of the effect in the scene */
  97403. name, scene) {
  97404. this._vertexBuffers = {};
  97405. this._maxSize = 0;
  97406. this._mainTextureDesiredSize = { width: 0, height: 0 };
  97407. this._shouldRender = true;
  97408. this._postProcesses = [];
  97409. this._textures = [];
  97410. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  97411. /**
  97412. * The clear color of the texture used to generate the glow map.
  97413. */
  97414. this.neutralColor = new BABYLON.Color4();
  97415. /**
  97416. * Specifies wether the highlight layer is enabled or not.
  97417. */
  97418. this.isEnabled = true;
  97419. /**
  97420. * An event triggered when the effect layer has been disposed.
  97421. */
  97422. this.onDisposeObservable = new BABYLON.Observable();
  97423. /**
  97424. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  97425. */
  97426. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  97427. /**
  97428. * An event triggered when the generated texture is being merged in the scene.
  97429. */
  97430. this.onBeforeComposeObservable = new BABYLON.Observable();
  97431. /**
  97432. * An event triggered when the generated texture has been merged in the scene.
  97433. */
  97434. this.onAfterComposeObservable = new BABYLON.Observable();
  97435. /**
  97436. * An event triggered when the efffect layer changes its size.
  97437. */
  97438. this.onSizeChangedObservable = new BABYLON.Observable();
  97439. this.name = name;
  97440. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97441. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  97442. if (!component) {
  97443. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  97444. this._scene._addComponent(component);
  97445. }
  97446. this._engine = this._scene.getEngine();
  97447. this._maxSize = this._engine.getCaps().maxTextureSize;
  97448. this._scene.effectLayers.push(this);
  97449. // Generate Buffers
  97450. this._generateIndexBuffer();
  97451. this._genrateVertexBuffer();
  97452. }
  97453. Object.defineProperty(EffectLayer.prototype, "camera", {
  97454. /**
  97455. * Gets the camera attached to the layer.
  97456. */
  97457. get: function () {
  97458. return this._effectLayerOptions.camera;
  97459. },
  97460. enumerable: true,
  97461. configurable: true
  97462. });
  97463. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  97464. /**
  97465. * Gets the rendering group id the layer should render in.
  97466. */
  97467. get: function () {
  97468. return this._effectLayerOptions.renderingGroupId;
  97469. },
  97470. enumerable: true,
  97471. configurable: true
  97472. });
  97473. /**
  97474. * Initializes the effect layer with the required options.
  97475. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  97476. */
  97477. EffectLayer.prototype._init = function (options) {
  97478. // Adapt options
  97479. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97480. this._setMainTextureSize();
  97481. this._createMainTexture();
  97482. this._createTextureAndPostProcesses();
  97483. this._mergeEffect = this._createMergeEffect();
  97484. };
  97485. /**
  97486. * Generates the index buffer of the full screen quad blending to the main canvas.
  97487. */
  97488. EffectLayer.prototype._generateIndexBuffer = function () {
  97489. // Indices
  97490. var indices = [];
  97491. indices.push(0);
  97492. indices.push(1);
  97493. indices.push(2);
  97494. indices.push(0);
  97495. indices.push(2);
  97496. indices.push(3);
  97497. this._indexBuffer = this._engine.createIndexBuffer(indices);
  97498. };
  97499. /**
  97500. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  97501. */
  97502. EffectLayer.prototype._genrateVertexBuffer = function () {
  97503. // VBO
  97504. var vertices = [];
  97505. vertices.push(1, 1);
  97506. vertices.push(-1, 1);
  97507. vertices.push(-1, -1);
  97508. vertices.push(1, -1);
  97509. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97510. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97511. };
  97512. /**
  97513. * Sets the main texture desired size which is the closest power of two
  97514. * of the engine canvas size.
  97515. */
  97516. EffectLayer.prototype._setMainTextureSize = function () {
  97517. if (this._effectLayerOptions.mainTextureFixedSize) {
  97518. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  97519. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  97520. }
  97521. else {
  97522. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  97523. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  97524. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  97525. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  97526. }
  97527. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  97528. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  97529. };
  97530. /**
  97531. * Creates the main texture for the effect layer.
  97532. */
  97533. EffectLayer.prototype._createMainTexture = function () {
  97534. var _this = this;
  97535. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  97536. width: this._mainTextureDesiredSize.width,
  97537. height: this._mainTextureDesiredSize.height
  97538. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97539. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  97540. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97541. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97542. this._mainTexture.anisotropicFilteringLevel = 1;
  97543. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97544. this._mainTexture.renderParticles = false;
  97545. this._mainTexture.renderList = null;
  97546. this._mainTexture.ignoreCameraViewport = true;
  97547. // Custom render function
  97548. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  97549. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  97550. var index;
  97551. var engine = _this._scene.getEngine();
  97552. if (depthOnlySubMeshes.length) {
  97553. engine.setColorWrite(false);
  97554. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  97555. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  97556. }
  97557. engine.setColorWrite(true);
  97558. }
  97559. for (index = 0; index < opaqueSubMeshes.length; index++) {
  97560. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  97561. }
  97562. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  97563. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  97564. }
  97565. for (index = 0; index < transparentSubMeshes.length; index++) {
  97566. _this._renderSubMesh(transparentSubMeshes.data[index]);
  97567. }
  97568. };
  97569. this._mainTexture.onClearObservable.add(function (engine) {
  97570. engine.clear(_this.neutralColor, true, true, true);
  97571. });
  97572. };
  97573. /**
  97574. * Checks for the readiness of the element composing the layer.
  97575. * @param subMesh the mesh to check for
  97576. * @param useInstances specify wether or not to use instances to render the mesh
  97577. * @param emissiveTexture the associated emissive texture used to generate the glow
  97578. * @return true if ready otherwise, false
  97579. */
  97580. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  97581. var material = subMesh.getMaterial();
  97582. if (!material) {
  97583. return false;
  97584. }
  97585. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  97586. return false;
  97587. }
  97588. var defines = [];
  97589. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97590. var mesh = subMesh.getMesh();
  97591. var uv1 = false;
  97592. var uv2 = false;
  97593. // Alpha test
  97594. if (material && material.needAlphaTesting()) {
  97595. var alphaTexture = material.getAlphaTestTexture();
  97596. if (alphaTexture) {
  97597. defines.push("#define ALPHATEST");
  97598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97599. alphaTexture.coordinatesIndex === 1) {
  97600. defines.push("#define DIFFUSEUV2");
  97601. uv2 = true;
  97602. }
  97603. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97604. defines.push("#define DIFFUSEUV1");
  97605. uv1 = true;
  97606. }
  97607. }
  97608. }
  97609. // Emissive
  97610. if (emissiveTexture) {
  97611. defines.push("#define EMISSIVE");
  97612. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97613. emissiveTexture.coordinatesIndex === 1) {
  97614. defines.push("#define EMISSIVEUV2");
  97615. uv2 = true;
  97616. }
  97617. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97618. defines.push("#define EMISSIVEUV1");
  97619. uv1 = true;
  97620. }
  97621. }
  97622. if (uv1) {
  97623. attribs.push(BABYLON.VertexBuffer.UVKind);
  97624. defines.push("#define UV1");
  97625. }
  97626. if (uv2) {
  97627. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97628. defines.push("#define UV2");
  97629. }
  97630. // Bones
  97631. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  97632. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  97633. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  97634. if (mesh.numBoneInfluencers > 4) {
  97635. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  97636. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  97637. }
  97638. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  97639. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  97640. }
  97641. else {
  97642. defines.push("#define NUM_BONE_INFLUENCERS 0");
  97643. }
  97644. // Morph targets
  97645. var manager = mesh.morphTargetManager;
  97646. var morphInfluencers = 0;
  97647. if (manager) {
  97648. if (manager.numInfluencers > 0) {
  97649. defines.push("#define MORPHTARGETS");
  97650. morphInfluencers = manager.numInfluencers;
  97651. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  97652. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  97653. }
  97654. }
  97655. // Instances
  97656. if (useInstances) {
  97657. defines.push("#define INSTANCES");
  97658. attribs.push("world0");
  97659. attribs.push("world1");
  97660. attribs.push("world2");
  97661. attribs.push("world3");
  97662. }
  97663. // Get correct effect
  97664. var join = defines.join("\n");
  97665. if (this._cachedDefines !== join) {
  97666. this._cachedDefines = join;
  97667. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  97668. }
  97669. return this._effectLayerMapGenerationEffect.isReady();
  97670. };
  97671. /**
  97672. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  97673. */
  97674. EffectLayer.prototype.render = function () {
  97675. var currentEffect = this._mergeEffect;
  97676. // Check
  97677. if (!currentEffect.isReady())
  97678. return;
  97679. for (var i = 0; i < this._postProcesses.length; i++) {
  97680. if (!this._postProcesses[i].isReady()) {
  97681. return;
  97682. }
  97683. }
  97684. var engine = this._scene.getEngine();
  97685. this.onBeforeComposeObservable.notifyObservers(this);
  97686. // Render
  97687. engine.enableEffect(currentEffect);
  97688. engine.setState(false);
  97689. // VBOs
  97690. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97691. // Cache
  97692. var previousAlphaMode = engine.getAlphaMode();
  97693. // Go Blend.
  97694. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  97695. // Blends the map on the main canvas.
  97696. this._internalRender(currentEffect);
  97697. // Restore Alpha
  97698. engine.setAlphaMode(previousAlphaMode);
  97699. this.onAfterComposeObservable.notifyObservers(this);
  97700. // Handle size changes.
  97701. var size = this._mainTexture.getSize();
  97702. this._setMainTextureSize();
  97703. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  97704. // Recreate RTT and post processes on size change.
  97705. this.onSizeChangedObservable.notifyObservers(this);
  97706. this._disposeTextureAndPostProcesses();
  97707. this._createMainTexture();
  97708. this._createTextureAndPostProcesses();
  97709. }
  97710. };
  97711. /**
  97712. * Determine if a given mesh will be used in the current effect.
  97713. * @param mesh mesh to test
  97714. * @returns true if the mesh will be used
  97715. */
  97716. EffectLayer.prototype.hasMesh = function (mesh) {
  97717. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  97718. return true;
  97719. }
  97720. return false;
  97721. };
  97722. /**
  97723. * Returns true if the layer contains information to display, otherwise false.
  97724. * @returns true if the glow layer should be rendered
  97725. */
  97726. EffectLayer.prototype.shouldRender = function () {
  97727. return this.isEnabled && this._shouldRender;
  97728. };
  97729. /**
  97730. * Returns true if the mesh should render, otherwise false.
  97731. * @param mesh The mesh to render
  97732. * @returns true if it should render otherwise false
  97733. */
  97734. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  97735. return true;
  97736. };
  97737. /**
  97738. * Returns true if the mesh should render, otherwise false.
  97739. * @param mesh The mesh to render
  97740. * @returns true if it should render otherwise false
  97741. */
  97742. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  97743. return true;
  97744. };
  97745. /**
  97746. * Renders the submesh passed in parameter to the generation map.
  97747. */
  97748. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  97749. var _this = this;
  97750. if (!this.shouldRender()) {
  97751. return;
  97752. }
  97753. var material = subMesh.getMaterial();
  97754. var mesh = subMesh.getRenderingMesh();
  97755. var scene = this._scene;
  97756. var engine = scene.getEngine();
  97757. if (!material) {
  97758. return;
  97759. }
  97760. // Do not block in blend mode.
  97761. if (material.needAlphaBlendingForMesh(mesh)) {
  97762. return;
  97763. }
  97764. // Culling
  97765. engine.setState(material.backFaceCulling);
  97766. // Managing instances
  97767. var batch = mesh._getInstancesRenderList(subMesh._id);
  97768. if (batch.mustReturn) {
  97769. return;
  97770. }
  97771. // Early Exit per mesh
  97772. if (!this._shouldRenderMesh(mesh)) {
  97773. return;
  97774. }
  97775. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97776. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  97777. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  97778. engine.enableEffect(this._effectLayerMapGenerationEffect);
  97779. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  97780. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  97781. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  97782. // Alpha test
  97783. if (material && material.needAlphaTesting()) {
  97784. var alphaTexture = material.getAlphaTestTexture();
  97785. if (alphaTexture) {
  97786. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  97787. var textureMatrix = alphaTexture.getTextureMatrix();
  97788. if (textureMatrix) {
  97789. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  97790. }
  97791. }
  97792. }
  97793. // Glow emissive only
  97794. if (this._emissiveTextureAndColor.texture) {
  97795. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  97796. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  97797. }
  97798. // Bones
  97799. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97800. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97801. }
  97802. // Morph targets
  97803. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  97804. // Draw
  97805. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  97806. }
  97807. else {
  97808. // Need to reset refresh rate of the main map
  97809. this._mainTexture.resetRefreshCounter();
  97810. }
  97811. };
  97812. /**
  97813. * Rebuild the required buffers.
  97814. * @hidden Internal use only.
  97815. */
  97816. EffectLayer.prototype._rebuild = function () {
  97817. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97818. if (vb) {
  97819. vb._rebuild();
  97820. }
  97821. this._generateIndexBuffer();
  97822. };
  97823. /**
  97824. * Dispose only the render target textures and post process.
  97825. */
  97826. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  97827. this._mainTexture.dispose();
  97828. for (var i = 0; i < this._postProcesses.length; i++) {
  97829. if (this._postProcesses[i]) {
  97830. this._postProcesses[i].dispose();
  97831. }
  97832. }
  97833. this._postProcesses = [];
  97834. for (var i = 0; i < this._textures.length; i++) {
  97835. if (this._textures[i]) {
  97836. this._textures[i].dispose();
  97837. }
  97838. }
  97839. this._textures = [];
  97840. };
  97841. /**
  97842. * Dispose the highlight layer and free resources.
  97843. */
  97844. EffectLayer.prototype.dispose = function () {
  97845. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97846. if (vertexBuffer) {
  97847. vertexBuffer.dispose();
  97848. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97849. }
  97850. if (this._indexBuffer) {
  97851. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97852. this._indexBuffer = null;
  97853. }
  97854. // Clean textures and post processes
  97855. this._disposeTextureAndPostProcesses();
  97856. // Remove from scene
  97857. var index = this._scene.effectLayers.indexOf(this, 0);
  97858. if (index > -1) {
  97859. this._scene.effectLayers.splice(index, 1);
  97860. }
  97861. // Callback
  97862. this.onDisposeObservable.notifyObservers(this);
  97863. this.onDisposeObservable.clear();
  97864. this.onBeforeRenderMainTextureObservable.clear();
  97865. this.onBeforeComposeObservable.clear();
  97866. this.onAfterComposeObservable.clear();
  97867. this.onSizeChangedObservable.clear();
  97868. };
  97869. /**
  97870. * Gets the class name of the effect layer
  97871. * @returns the string with the class name of the effect layer
  97872. */
  97873. EffectLayer.prototype.getClassName = function () {
  97874. return "EffectLayer";
  97875. };
  97876. /**
  97877. * Creates an effect layer from parsed effect layer data
  97878. * @param parsedEffectLayer defines effect layer data
  97879. * @param scene defines the current scene
  97880. * @param rootUrl defines the root URL containing the effect layer information
  97881. * @returns a parsed effect Layer
  97882. */
  97883. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  97884. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  97885. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  97886. };
  97887. __decorate([
  97888. BABYLON.serialize()
  97889. ], EffectLayer.prototype, "name", void 0);
  97890. __decorate([
  97891. BABYLON.serializeAsColor4()
  97892. ], EffectLayer.prototype, "neutralColor", void 0);
  97893. __decorate([
  97894. BABYLON.serialize()
  97895. ], EffectLayer.prototype, "isEnabled", void 0);
  97896. __decorate([
  97897. BABYLON.serializeAsCameraReference()
  97898. ], EffectLayer.prototype, "camera", null);
  97899. __decorate([
  97900. BABYLON.serialize()
  97901. ], EffectLayer.prototype, "renderingGroupId", null);
  97902. return EffectLayer;
  97903. }());
  97904. BABYLON.EffectLayer = EffectLayer;
  97905. })(BABYLON || (BABYLON = {}));
  97906. //# sourceMappingURL=babylon.effectLayer.js.map
  97907. var BABYLON;
  97908. (function (BABYLON) {
  97909. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  97910. for (var index = 0; index < this.effectLayers.length; index++) {
  97911. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  97912. return this.effectLayers[index];
  97913. }
  97914. }
  97915. return null;
  97916. };
  97917. /**
  97918. * Special Glow Blur post process only blurring the alpha channel
  97919. * It enforces keeping the most luminous color in the color channel.
  97920. */
  97921. var GlowBlurPostProcess = /** @class */ (function (_super) {
  97922. __extends(GlowBlurPostProcess, _super);
  97923. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  97924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  97925. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  97926. _this.direction = direction;
  97927. _this.kernel = kernel;
  97928. _this.onApplyObservable.add(function (effect) {
  97929. effect.setFloat2("screenSize", _this.width, _this.height);
  97930. effect.setVector2("direction", _this.direction);
  97931. effect.setFloat("blurWidth", _this.kernel);
  97932. });
  97933. return _this;
  97934. }
  97935. return GlowBlurPostProcess;
  97936. }(BABYLON.PostProcess));
  97937. /**
  97938. * The highlight layer Helps adding a glow effect around a mesh.
  97939. *
  97940. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97941. * glowy meshes to your scene.
  97942. *
  97943. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  97944. */
  97945. var HighlightLayer = /** @class */ (function (_super) {
  97946. __extends(HighlightLayer, _super);
  97947. /**
  97948. * Instantiates a new highlight Layer and references it to the scene..
  97949. * @param name The name of the layer
  97950. * @param scene The scene to use the layer in
  97951. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  97952. */
  97953. function HighlightLayer(name, scene, options) {
  97954. var _this = _super.call(this, name, scene) || this;
  97955. _this.name = name;
  97956. /**
  97957. * Specifies whether or not the inner glow is ACTIVE in the layer.
  97958. */
  97959. _this.innerGlow = true;
  97960. /**
  97961. * Specifies whether or not the outer glow is ACTIVE in the layer.
  97962. */
  97963. _this.outerGlow = true;
  97964. /**
  97965. * An event triggered when the highlight layer is being blurred.
  97966. */
  97967. _this.onBeforeBlurObservable = new BABYLON.Observable();
  97968. /**
  97969. * An event triggered when the highlight layer has been blurred.
  97970. */
  97971. _this.onAfterBlurObservable = new BABYLON.Observable();
  97972. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  97973. _this._meshes = {};
  97974. _this._excludedMeshes = {};
  97975. _this.neutralColor = HighlightLayer.NeutralColor;
  97976. // Warn on stencil
  97977. if (!_this._engine.isStencilEnable) {
  97978. 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 }");
  97979. }
  97980. // Adapt options
  97981. _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);
  97982. // Initialize the layer
  97983. _this._init({
  97984. alphaBlendingMode: _this._options.alphaBlendingMode,
  97985. camera: _this._options.camera,
  97986. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97987. mainTextureRatio: _this._options.mainTextureRatio,
  97988. renderingGroupId: _this._options.renderingGroupId
  97989. });
  97990. // Do not render as long as no meshes have been added
  97991. _this._shouldRender = false;
  97992. return _this;
  97993. }
  97994. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97995. /**
  97996. * Gets the horizontal size of the blur.
  97997. */
  97998. get: function () {
  97999. return this._horizontalBlurPostprocess.kernel;
  98000. },
  98001. /**
  98002. * Specifies the horizontal size of the blur.
  98003. */
  98004. set: function (value) {
  98005. this._horizontalBlurPostprocess.kernel = value;
  98006. },
  98007. enumerable: true,
  98008. configurable: true
  98009. });
  98010. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  98011. /**
  98012. * Gets the vertical size of the blur.
  98013. */
  98014. get: function () {
  98015. return this._verticalBlurPostprocess.kernel;
  98016. },
  98017. /**
  98018. * Specifies the vertical size of the blur.
  98019. */
  98020. set: function (value) {
  98021. this._verticalBlurPostprocess.kernel = value;
  98022. },
  98023. enumerable: true,
  98024. configurable: true
  98025. });
  98026. /**
  98027. * Get the effect name of the layer.
  98028. * @return The effect name
  98029. */
  98030. HighlightLayer.prototype.getEffectName = function () {
  98031. return HighlightLayer.EffectName;
  98032. };
  98033. /**
  98034. * Create the merge effect. This is the shader use to blit the information back
  98035. * to the main canvas at the end of the scene rendering.
  98036. */
  98037. HighlightLayer.prototype._createMergeEffect = function () {
  98038. // Effect
  98039. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  98040. };
  98041. /**
  98042. * Creates the render target textures and post processes used in the highlight layer.
  98043. */
  98044. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  98045. var _this = this;
  98046. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  98047. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  98048. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98049. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98050. var textureType = 0;
  98051. if (this._engine.getCaps().textureHalfFloatRender) {
  98052. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98053. }
  98054. else {
  98055. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98056. }
  98057. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  98058. width: blurTextureWidth,
  98059. height: blurTextureHeight
  98060. }, this._scene, false, true, textureType);
  98061. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98062. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98063. this._blurTexture.anisotropicFilteringLevel = 16;
  98064. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  98065. this._blurTexture.renderParticles = false;
  98066. this._blurTexture.ignoreCameraViewport = true;
  98067. this._textures = [this._blurTexture];
  98068. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  98069. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98070. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  98071. effect.setTexture("textureSampler", _this._mainTexture);
  98072. });
  98073. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98074. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  98075. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  98076. });
  98077. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  98078. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  98079. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  98080. });
  98081. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  98082. }
  98083. else {
  98084. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  98085. width: blurTextureWidth,
  98086. height: blurTextureHeight
  98087. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98088. this._horizontalBlurPostprocess.width = blurTextureWidth;
  98089. this._horizontalBlurPostprocess.height = blurTextureHeight;
  98090. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  98091. effect.setTexture("textureSampler", _this._mainTexture);
  98092. });
  98093. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  98094. width: blurTextureWidth,
  98095. height: blurTextureHeight
  98096. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98097. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  98098. }
  98099. this._mainTexture.onAfterUnbindObservable.add(function () {
  98100. _this.onBeforeBlurObservable.notifyObservers(_this);
  98101. var internalTexture = _this._blurTexture.getInternalTexture();
  98102. if (internalTexture) {
  98103. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  98104. }
  98105. _this.onAfterBlurObservable.notifyObservers(_this);
  98106. });
  98107. // Prevent autoClear.
  98108. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98109. };
  98110. /**
  98111. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98112. */
  98113. HighlightLayer.prototype.needStencil = function () {
  98114. return true;
  98115. };
  98116. /**
  98117. * Checks for the readiness of the element composing the layer.
  98118. * @param subMesh the mesh to check for
  98119. * @param useInstances specify wether or not to use instances to render the mesh
  98120. * @param emissiveTexture the associated emissive texture used to generate the glow
  98121. * @return true if ready otherwise, false
  98122. */
  98123. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  98124. var material = subMesh.getMaterial();
  98125. var mesh = subMesh.getRenderingMesh();
  98126. if (!material || !mesh || !this._meshes) {
  98127. return false;
  98128. }
  98129. var emissiveTexture = null;
  98130. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98131. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98132. emissiveTexture = material.emissiveTexture;
  98133. }
  98134. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98135. };
  98136. /**
  98137. * Implementation specific of rendering the generating effect on the main canvas.
  98138. * @param effect The effect used to render through
  98139. */
  98140. HighlightLayer.prototype._internalRender = function (effect) {
  98141. // Texture
  98142. effect.setTexture("textureSampler", this._blurTexture);
  98143. // Cache
  98144. var engine = this._engine;
  98145. var previousStencilBuffer = engine.getStencilBuffer();
  98146. var previousStencilFunction = engine.getStencilFunction();
  98147. var previousStencilMask = engine.getStencilMask();
  98148. var previousStencilOperationPass = engine.getStencilOperationPass();
  98149. var previousStencilOperationFail = engine.getStencilOperationFail();
  98150. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  98151. var previousStencilReference = engine.getStencilFunctionReference();
  98152. // Stencil operations
  98153. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  98154. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  98155. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  98156. // Draw order
  98157. engine.setStencilMask(0x00);
  98158. engine.setStencilBuffer(true);
  98159. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  98160. // 2 passes inner outer
  98161. if (this.outerGlow) {
  98162. effect.setFloat("offset", 0);
  98163. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  98164. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98165. }
  98166. if (this.innerGlow) {
  98167. effect.setFloat("offset", 1);
  98168. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  98169. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98170. }
  98171. // Restore Cache
  98172. engine.setStencilFunction(previousStencilFunction);
  98173. engine.setStencilMask(previousStencilMask);
  98174. engine.setStencilBuffer(previousStencilBuffer);
  98175. engine.setStencilOperationPass(previousStencilOperationPass);
  98176. engine.setStencilOperationFail(previousStencilOperationFail);
  98177. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  98178. engine.setStencilFunctionReference(previousStencilReference);
  98179. };
  98180. /**
  98181. * Returns true if the layer contains information to display, otherwise false.
  98182. */
  98183. HighlightLayer.prototype.shouldRender = function () {
  98184. if (_super.prototype.shouldRender.call(this)) {
  98185. return this._meshes ? true : false;
  98186. }
  98187. return false;
  98188. };
  98189. /**
  98190. * Returns true if the mesh should render, otherwise false.
  98191. * @param mesh The mesh to render
  98192. * @returns true if it should render otherwise false
  98193. */
  98194. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  98195. // Excluded Mesh
  98196. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  98197. return false;
  98198. }
  98199. ;
  98200. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98201. return false;
  98202. }
  98203. return true;
  98204. };
  98205. /**
  98206. * Sets the required values for both the emissive texture and and the main color.
  98207. */
  98208. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98209. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98210. if (highlightLayerMesh) {
  98211. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  98212. }
  98213. else {
  98214. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98215. }
  98216. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98217. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98218. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  98219. }
  98220. else {
  98221. this._emissiveTextureAndColor.texture = null;
  98222. }
  98223. };
  98224. /**
  98225. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  98226. * @param mesh The mesh to exclude from the highlight layer
  98227. */
  98228. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  98229. if (!this._excludedMeshes) {
  98230. return;
  98231. }
  98232. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98233. if (!meshExcluded) {
  98234. this._excludedMeshes[mesh.uniqueId] = {
  98235. mesh: mesh,
  98236. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  98237. mesh.getEngine().setStencilBuffer(false);
  98238. }),
  98239. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  98240. mesh.getEngine().setStencilBuffer(true);
  98241. }),
  98242. };
  98243. }
  98244. };
  98245. /**
  98246. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  98247. * @param mesh The mesh to highlight
  98248. */
  98249. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  98250. if (!this._excludedMeshes) {
  98251. return;
  98252. }
  98253. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98254. if (meshExcluded) {
  98255. if (meshExcluded.beforeRender) {
  98256. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  98257. }
  98258. if (meshExcluded.afterRender) {
  98259. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  98260. }
  98261. }
  98262. this._excludedMeshes[mesh.uniqueId] = null;
  98263. };
  98264. /**
  98265. * Determine if a given mesh will be highlighted by the current HighlightLayer
  98266. * @param mesh mesh to test
  98267. * @returns true if the mesh will be highlighted by the current HighlightLayer
  98268. */
  98269. HighlightLayer.prototype.hasMesh = function (mesh) {
  98270. if (!this._meshes) {
  98271. return false;
  98272. }
  98273. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98274. return false;
  98275. }
  98276. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  98277. };
  98278. /**
  98279. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  98280. * @param mesh The mesh to highlight
  98281. * @param color The color of the highlight
  98282. * @param glowEmissiveOnly Extract the glow from the emissive texture
  98283. */
  98284. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  98285. var _this = this;
  98286. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  98287. if (!this._meshes) {
  98288. return;
  98289. }
  98290. var meshHighlight = this._meshes[mesh.uniqueId];
  98291. if (meshHighlight) {
  98292. meshHighlight.color = color;
  98293. }
  98294. else {
  98295. this._meshes[mesh.uniqueId] = {
  98296. mesh: mesh,
  98297. color: color,
  98298. // Lambda required for capture due to Observable this context
  98299. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  98300. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  98301. _this._defaultStencilReference(mesh);
  98302. }
  98303. else {
  98304. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  98305. }
  98306. }),
  98307. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  98308. glowEmissiveOnly: glowEmissiveOnly
  98309. };
  98310. mesh.onDisposeObservable.add(function () {
  98311. _this._disposeMesh(mesh);
  98312. });
  98313. }
  98314. this._shouldRender = true;
  98315. };
  98316. /**
  98317. * Remove a mesh from the highlight layer in order to make it stop glowing.
  98318. * @param mesh The mesh to highlight
  98319. */
  98320. HighlightLayer.prototype.removeMesh = function (mesh) {
  98321. if (!this._meshes) {
  98322. return;
  98323. }
  98324. var meshHighlight = this._meshes[mesh.uniqueId];
  98325. if (meshHighlight) {
  98326. if (meshHighlight.observerHighlight) {
  98327. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98328. }
  98329. if (meshHighlight.observerDefault) {
  98330. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98331. }
  98332. delete this._meshes[mesh.uniqueId];
  98333. }
  98334. this._shouldRender = false;
  98335. for (var meshHighlightToCheck in this._meshes) {
  98336. if (this._meshes[meshHighlightToCheck]) {
  98337. this._shouldRender = true;
  98338. break;
  98339. }
  98340. }
  98341. };
  98342. /**
  98343. * Force the stencil to the normal expected value for none glowing parts
  98344. */
  98345. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  98346. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  98347. };
  98348. /**
  98349. * Free any resources and references associated to a mesh.
  98350. * Internal use
  98351. * @param mesh The mesh to free.
  98352. */
  98353. HighlightLayer.prototype._disposeMesh = function (mesh) {
  98354. this.removeMesh(mesh);
  98355. this.removeExcludedMesh(mesh);
  98356. };
  98357. /**
  98358. * Dispose the highlight layer and free resources.
  98359. */
  98360. HighlightLayer.prototype.dispose = function () {
  98361. if (this._meshes) {
  98362. // Clean mesh references
  98363. for (var id in this._meshes) {
  98364. var meshHighlight = this._meshes[id];
  98365. if (meshHighlight && meshHighlight.mesh) {
  98366. if (meshHighlight.observerHighlight) {
  98367. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98368. }
  98369. if (meshHighlight.observerDefault) {
  98370. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98371. }
  98372. }
  98373. }
  98374. this._meshes = null;
  98375. }
  98376. if (this._excludedMeshes) {
  98377. for (var id in this._excludedMeshes) {
  98378. var meshHighlight = this._excludedMeshes[id];
  98379. if (meshHighlight) {
  98380. if (meshHighlight.beforeRender) {
  98381. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  98382. }
  98383. if (meshHighlight.afterRender) {
  98384. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  98385. }
  98386. }
  98387. }
  98388. this._excludedMeshes = null;
  98389. }
  98390. _super.prototype.dispose.call(this);
  98391. };
  98392. /**
  98393. * Gets the class name of the effect layer
  98394. * @returns the string with the class name of the effect layer
  98395. */
  98396. HighlightLayer.prototype.getClassName = function () {
  98397. return "HighlightLayer";
  98398. };
  98399. /**
  98400. * Serializes this Highlight layer
  98401. * @returns a serialized Highlight layer object
  98402. */
  98403. HighlightLayer.prototype.serialize = function () {
  98404. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98405. serializationObject.customType = "BABYLON.HighlightLayer";
  98406. // Highlighted meshes
  98407. serializationObject.meshes = [];
  98408. if (this._meshes) {
  98409. for (var m in this._meshes) {
  98410. var mesh = this._meshes[m];
  98411. if (mesh) {
  98412. serializationObject.meshes.push({
  98413. glowEmissiveOnly: mesh.glowEmissiveOnly,
  98414. color: mesh.color.asArray(),
  98415. meshId: mesh.mesh.id
  98416. });
  98417. }
  98418. }
  98419. }
  98420. // Excluded meshes
  98421. serializationObject.excludedMeshes = [];
  98422. if (this._excludedMeshes) {
  98423. for (var e in this._excludedMeshes) {
  98424. var excludedMesh = this._excludedMeshes[e];
  98425. if (excludedMesh) {
  98426. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  98427. }
  98428. }
  98429. }
  98430. return serializationObject;
  98431. };
  98432. /**
  98433. * Creates a Highlight layer from parsed Highlight layer data
  98434. * @param parsedHightlightLayer defines the Highlight layer data
  98435. * @param scene defines the current scene
  98436. * @param rootUrl defines the root URL containing the Highlight layer information
  98437. * @returns a parsed Highlight layer
  98438. */
  98439. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  98440. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  98441. var index;
  98442. // Excluded meshes
  98443. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  98444. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  98445. if (mesh) {
  98446. hl.addExcludedMesh(mesh);
  98447. }
  98448. }
  98449. // Included meshes
  98450. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  98451. var highlightedMesh = parsedHightlightLayer.meshes[index];
  98452. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  98453. if (mesh) {
  98454. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  98455. }
  98456. }
  98457. return hl;
  98458. };
  98459. /**
  98460. * Effect Name of the highlight layer.
  98461. */
  98462. HighlightLayer.EffectName = "HighlightLayer";
  98463. /**
  98464. * The neutral color used during the preparation of the glow effect.
  98465. * This is black by default as the blend operation is a blend operation.
  98466. */
  98467. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  98468. /**
  98469. * Stencil value used for glowing meshes.
  98470. */
  98471. HighlightLayer.GlowingMeshStencilReference = 0x02;
  98472. /**
  98473. * Stencil value used for the other meshes in the scene.
  98474. */
  98475. HighlightLayer.NormalMeshStencilReference = 0x01;
  98476. __decorate([
  98477. BABYLON.serialize()
  98478. ], HighlightLayer.prototype, "innerGlow", void 0);
  98479. __decorate([
  98480. BABYLON.serialize()
  98481. ], HighlightLayer.prototype, "outerGlow", void 0);
  98482. __decorate([
  98483. BABYLON.serialize()
  98484. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  98485. __decorate([
  98486. BABYLON.serialize()
  98487. ], HighlightLayer.prototype, "blurVerticalSize", null);
  98488. __decorate([
  98489. BABYLON.serialize("options")
  98490. ], HighlightLayer.prototype, "_options", void 0);
  98491. return HighlightLayer;
  98492. }(BABYLON.EffectLayer));
  98493. BABYLON.HighlightLayer = HighlightLayer;
  98494. })(BABYLON || (BABYLON = {}));
  98495. //# sourceMappingURL=babylon.highlightLayer.js.map
  98496. var BABYLON;
  98497. (function (BABYLON) {
  98498. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  98499. for (var index = 0; index < this.effectLayers.length; index++) {
  98500. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  98501. return this.effectLayers[index];
  98502. }
  98503. }
  98504. return null;
  98505. };
  98506. /**
  98507. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  98508. *
  98509. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  98510. * glowy meshes to your scene.
  98511. *
  98512. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  98513. */
  98514. var GlowLayer = /** @class */ (function (_super) {
  98515. __extends(GlowLayer, _super);
  98516. /**
  98517. * Instantiates a new glow Layer and references it to the scene.
  98518. * @param name The name of the layer
  98519. * @param scene The scene to use the layer in
  98520. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  98521. */
  98522. function GlowLayer(name, scene, options) {
  98523. var _this = _super.call(this, name, scene) || this;
  98524. _this._intensity = 1.0;
  98525. _this._includedOnlyMeshes = [];
  98526. _this._excludedMeshes = [];
  98527. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  98528. // Adapt options
  98529. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  98530. // Initialize the layer
  98531. _this._init({
  98532. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  98533. camera: _this._options.camera,
  98534. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  98535. mainTextureRatio: _this._options.mainTextureRatio,
  98536. renderingGroupId: _this._options.renderingGroupId
  98537. });
  98538. return _this;
  98539. }
  98540. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  98541. /**
  98542. * Gets the kernel size of the blur.
  98543. */
  98544. get: function () {
  98545. return this._horizontalBlurPostprocess1.kernel;
  98546. },
  98547. /**
  98548. * Sets the kernel size of the blur.
  98549. */
  98550. set: function (value) {
  98551. this._horizontalBlurPostprocess1.kernel = value;
  98552. this._verticalBlurPostprocess1.kernel = value;
  98553. this._horizontalBlurPostprocess2.kernel = value;
  98554. this._verticalBlurPostprocess2.kernel = value;
  98555. },
  98556. enumerable: true,
  98557. configurable: true
  98558. });
  98559. Object.defineProperty(GlowLayer.prototype, "intensity", {
  98560. /**
  98561. * Gets the glow intensity.
  98562. */
  98563. get: function () {
  98564. return this._intensity;
  98565. },
  98566. /**
  98567. * Sets the glow intensity.
  98568. */
  98569. set: function (value) {
  98570. this._intensity = value;
  98571. },
  98572. enumerable: true,
  98573. configurable: true
  98574. });
  98575. /**
  98576. * Get the effect name of the layer.
  98577. * @return The effect name
  98578. */
  98579. GlowLayer.prototype.getEffectName = function () {
  98580. return GlowLayer.EffectName;
  98581. };
  98582. /**
  98583. * Create the merge effect. This is the shader use to blit the information back
  98584. * to the main canvas at the end of the scene rendering.
  98585. */
  98586. GlowLayer.prototype._createMergeEffect = function () {
  98587. // Effect
  98588. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  98589. };
  98590. /**
  98591. * Creates the render target textures and post processes used in the glow layer.
  98592. */
  98593. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  98594. var _this = this;
  98595. var blurTextureWidth = this._mainTextureDesiredSize.width;
  98596. var blurTextureHeight = this._mainTextureDesiredSize.height;
  98597. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98598. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98599. var textureType = 0;
  98600. if (this._engine.getCaps().textureHalfFloatRender) {
  98601. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98602. }
  98603. else {
  98604. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98605. }
  98606. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  98607. width: blurTextureWidth,
  98608. height: blurTextureHeight
  98609. }, this._scene, false, true, textureType);
  98610. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98611. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98612. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98613. this._blurTexture1.renderParticles = false;
  98614. this._blurTexture1.ignoreCameraViewport = true;
  98615. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  98616. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  98617. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  98618. width: blurTextureWidth2,
  98619. height: blurTextureHeight2
  98620. }, this._scene, false, true, textureType);
  98621. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98622. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98623. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98624. this._blurTexture2.renderParticles = false;
  98625. this._blurTexture2.ignoreCameraViewport = true;
  98626. this._textures = [this._blurTexture1, this._blurTexture2];
  98627. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98628. width: blurTextureWidth,
  98629. height: blurTextureHeight
  98630. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98631. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  98632. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  98633. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  98634. effect.setTexture("textureSampler", _this._mainTexture);
  98635. });
  98636. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98637. width: blurTextureWidth,
  98638. height: blurTextureHeight
  98639. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98640. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98641. width: blurTextureWidth2,
  98642. height: blurTextureHeight2
  98643. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98644. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  98645. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  98646. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  98647. effect.setTexture("textureSampler", _this._blurTexture1);
  98648. });
  98649. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98650. width: blurTextureWidth2,
  98651. height: blurTextureHeight2
  98652. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98653. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98654. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  98655. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98656. this._mainTexture.samples = this._options.mainTextureSamples;
  98657. this._mainTexture.onAfterUnbindObservable.add(function () {
  98658. var internalTexture = _this._blurTexture1.getInternalTexture();
  98659. if (internalTexture) {
  98660. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  98661. internalTexture = _this._blurTexture2.getInternalTexture();
  98662. if (internalTexture) {
  98663. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  98664. }
  98665. }
  98666. });
  98667. // Prevent autoClear.
  98668. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98669. };
  98670. /**
  98671. * Checks for the readiness of the element composing the layer.
  98672. * @param subMesh the mesh to check for
  98673. * @param useInstances specify wether or not to use instances to render the mesh
  98674. * @param emissiveTexture the associated emissive texture used to generate the glow
  98675. * @return true if ready otherwise, false
  98676. */
  98677. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  98678. var material = subMesh.getMaterial();
  98679. var mesh = subMesh.getRenderingMesh();
  98680. if (!material || !mesh) {
  98681. return false;
  98682. }
  98683. var emissiveTexture = material.emissiveTexture;
  98684. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98685. };
  98686. /**
  98687. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98688. */
  98689. GlowLayer.prototype.needStencil = function () {
  98690. return false;
  98691. };
  98692. /**
  98693. * Implementation specific of rendering the generating effect on the main canvas.
  98694. * @param effect The effect used to render through
  98695. */
  98696. GlowLayer.prototype._internalRender = function (effect) {
  98697. // Texture
  98698. effect.setTexture("textureSampler", this._blurTexture1);
  98699. effect.setTexture("textureSampler2", this._blurTexture2);
  98700. effect.setFloat("offset", this._intensity);
  98701. // Cache
  98702. var engine = this._engine;
  98703. var previousStencilBuffer = engine.getStencilBuffer();
  98704. // Draw order
  98705. engine.setStencilBuffer(false);
  98706. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98707. // Draw order
  98708. engine.setStencilBuffer(previousStencilBuffer);
  98709. };
  98710. /**
  98711. * Sets the required values for both the emissive texture and and the main color.
  98712. */
  98713. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98714. var textureLevel = 1.0;
  98715. if (this.customEmissiveTextureSelector) {
  98716. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  98717. }
  98718. else {
  98719. if (material) {
  98720. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98721. if (this._emissiveTextureAndColor.texture) {
  98722. textureLevel = this._emissiveTextureAndColor.texture.level;
  98723. }
  98724. }
  98725. else {
  98726. this._emissiveTextureAndColor.texture = null;
  98727. }
  98728. }
  98729. if (this.customEmissiveColorSelector) {
  98730. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  98731. }
  98732. else {
  98733. if (material.emissiveColor) {
  98734. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  98735. }
  98736. else {
  98737. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98738. }
  98739. }
  98740. };
  98741. /**
  98742. * Returns true if the mesh should render, otherwise false.
  98743. * @param mesh The mesh to render
  98744. * @returns true if it should render otherwise false
  98745. */
  98746. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  98747. return this.hasMesh(mesh);
  98748. };
  98749. /**
  98750. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  98751. * @param mesh The mesh to exclude from the glow layer
  98752. */
  98753. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  98754. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  98755. this._excludedMeshes.push(mesh.uniqueId);
  98756. }
  98757. };
  98758. /**
  98759. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  98760. * @param mesh The mesh to remove
  98761. */
  98762. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  98763. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  98764. if (index !== -1) {
  98765. this._excludedMeshes.splice(index, 1);
  98766. }
  98767. };
  98768. /**
  98769. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  98770. * @param mesh The mesh to include in the glow layer
  98771. */
  98772. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  98773. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  98774. this._includedOnlyMeshes.push(mesh.uniqueId);
  98775. }
  98776. };
  98777. /**
  98778. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  98779. * @param mesh The mesh to remove
  98780. */
  98781. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  98782. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  98783. if (index !== -1) {
  98784. this._includedOnlyMeshes.splice(index, 1);
  98785. }
  98786. };
  98787. /**
  98788. * Determine if a given mesh will be used in the glow layer
  98789. * @param mesh The mesh to test
  98790. * @returns true if the mesh will be highlighted by the current glow layer
  98791. */
  98792. GlowLayer.prototype.hasMesh = function (mesh) {
  98793. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98794. return false;
  98795. }
  98796. // Included Mesh
  98797. if (this._includedOnlyMeshes.length) {
  98798. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  98799. }
  98800. ;
  98801. // Excluded Mesh
  98802. if (this._excludedMeshes.length) {
  98803. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  98804. }
  98805. ;
  98806. return true;
  98807. };
  98808. /**
  98809. * Free any resources and references associated to a mesh.
  98810. * Internal use
  98811. * @param mesh The mesh to free.
  98812. */
  98813. GlowLayer.prototype._disposeMesh = function (mesh) {
  98814. this.removeIncludedOnlyMesh(mesh);
  98815. this.removeExcludedMesh(mesh);
  98816. };
  98817. /**
  98818. * Gets the class name of the effect layer
  98819. * @returns the string with the class name of the effect layer
  98820. */
  98821. GlowLayer.prototype.getClassName = function () {
  98822. return "GlowLayer";
  98823. };
  98824. /**
  98825. * Serializes this glow layer
  98826. * @returns a serialized glow layer object
  98827. */
  98828. GlowLayer.prototype.serialize = function () {
  98829. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98830. serializationObject.customType = "BABYLON.GlowLayer";
  98831. var index;
  98832. // Included meshes
  98833. serializationObject.includedMeshes = [];
  98834. if (this._includedOnlyMeshes.length) {
  98835. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  98836. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  98837. if (mesh) {
  98838. serializationObject.includedMeshes.push(mesh.id);
  98839. }
  98840. }
  98841. }
  98842. // Excluded meshes
  98843. serializationObject.excludedMeshes = [];
  98844. if (this._excludedMeshes.length) {
  98845. for (index = 0; index < this._excludedMeshes.length; index++) {
  98846. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  98847. if (mesh) {
  98848. serializationObject.excludedMeshes.push(mesh.id);
  98849. }
  98850. }
  98851. }
  98852. return serializationObject;
  98853. };
  98854. /**
  98855. * Creates a Glow Layer from parsed glow layer data
  98856. * @param parsedGlowLayer defines glow layer data
  98857. * @param scene defines the current scene
  98858. * @param rootUrl defines the root URL containing the glow layer information
  98859. * @returns a parsed Glow Layer
  98860. */
  98861. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  98862. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  98863. var index;
  98864. // Excluded meshes
  98865. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  98866. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  98867. if (mesh) {
  98868. gl.addExcludedMesh(mesh);
  98869. }
  98870. }
  98871. // Included meshes
  98872. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  98873. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  98874. if (mesh) {
  98875. gl.addIncludedOnlyMesh(mesh);
  98876. }
  98877. }
  98878. return gl;
  98879. };
  98880. /**
  98881. * Effect Name of the layer.
  98882. */
  98883. GlowLayer.EffectName = "GlowLayer";
  98884. /**
  98885. * The default blur kernel size used for the glow.
  98886. */
  98887. GlowLayer.DefaultBlurKernelSize = 32;
  98888. /**
  98889. * The default texture size ratio used for the glow.
  98890. */
  98891. GlowLayer.DefaultTextureRatio = 0.5;
  98892. __decorate([
  98893. BABYLON.serialize()
  98894. ], GlowLayer.prototype, "blurKernelSize", null);
  98895. __decorate([
  98896. BABYLON.serialize()
  98897. ], GlowLayer.prototype, "intensity", null);
  98898. __decorate([
  98899. BABYLON.serialize("options")
  98900. ], GlowLayer.prototype, "_options", void 0);
  98901. return GlowLayer;
  98902. }(BABYLON.EffectLayer));
  98903. BABYLON.GlowLayer = GlowLayer;
  98904. })(BABYLON || (BABYLON = {}));
  98905. //# sourceMappingURL=babylon.glowLayer.js.map
  98906. var BABYLON;
  98907. (function (BABYLON) {
  98908. /**
  98909. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  98910. */
  98911. var AssetTaskState;
  98912. (function (AssetTaskState) {
  98913. /**
  98914. * Initialization
  98915. */
  98916. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  98917. /**
  98918. * Running
  98919. */
  98920. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  98921. /**
  98922. * Done
  98923. */
  98924. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  98925. /**
  98926. * Error
  98927. */
  98928. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  98929. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  98930. /**
  98931. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  98932. */
  98933. var AbstractAssetTask = /** @class */ (function () {
  98934. /**
  98935. * Creates a new {BABYLON.AssetsManager}
  98936. * @param name defines the name of the task
  98937. */
  98938. function AbstractAssetTask(
  98939. /**
  98940. * Task name
  98941. */ name) {
  98942. this.name = name;
  98943. this._isCompleted = false;
  98944. this._taskState = AssetTaskState.INIT;
  98945. }
  98946. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  98947. /**
  98948. * Get if the task is completed
  98949. */
  98950. get: function () {
  98951. return this._isCompleted;
  98952. },
  98953. enumerable: true,
  98954. configurable: true
  98955. });
  98956. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  98957. /**
  98958. * Gets the current state of the task
  98959. */
  98960. get: function () {
  98961. return this._taskState;
  98962. },
  98963. enumerable: true,
  98964. configurable: true
  98965. });
  98966. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  98967. /**
  98968. * Gets the current error object (if task is in error)
  98969. */
  98970. get: function () {
  98971. return this._errorObject;
  98972. },
  98973. enumerable: true,
  98974. configurable: true
  98975. });
  98976. /**
  98977. * Internal only
  98978. * @hidden
  98979. */
  98980. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  98981. if (this._errorObject) {
  98982. return;
  98983. }
  98984. this._errorObject = {
  98985. message: message,
  98986. exception: exception
  98987. };
  98988. };
  98989. /**
  98990. * Execute the current task
  98991. * @param scene defines the scene where you want your assets to be loaded
  98992. * @param onSuccess is a callback called when the task is successfully executed
  98993. * @param onError is a callback called if an error occurs
  98994. */
  98995. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98996. var _this = this;
  98997. this._taskState = AssetTaskState.RUNNING;
  98998. this.runTask(scene, function () {
  98999. _this.onDoneCallback(onSuccess, onError);
  99000. }, function (msg, exception) {
  99001. _this.onErrorCallback(onError, msg, exception);
  99002. });
  99003. };
  99004. /**
  99005. * Execute the current task
  99006. * @param scene defines the scene where you want your assets to be loaded
  99007. * @param onSuccess is a callback called when the task is successfully executed
  99008. * @param onError is a callback called if an error occurs
  99009. */
  99010. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99011. throw new Error("runTask is not implemented");
  99012. };
  99013. /**
  99014. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  99015. * This can be used with failed tasks that have the reason for failure fixed.
  99016. */
  99017. AbstractAssetTask.prototype.reset = function () {
  99018. this._taskState = AssetTaskState.INIT;
  99019. };
  99020. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  99021. this._taskState = AssetTaskState.ERROR;
  99022. this._errorObject = {
  99023. message: message,
  99024. exception: exception
  99025. };
  99026. if (this.onError) {
  99027. this.onError(this, message, exception);
  99028. }
  99029. onError();
  99030. };
  99031. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  99032. try {
  99033. this._taskState = AssetTaskState.DONE;
  99034. this._isCompleted = true;
  99035. if (this.onSuccess) {
  99036. this.onSuccess(this);
  99037. }
  99038. onSuccess();
  99039. }
  99040. catch (e) {
  99041. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  99042. }
  99043. };
  99044. return AbstractAssetTask;
  99045. }());
  99046. BABYLON.AbstractAssetTask = AbstractAssetTask;
  99047. /**
  99048. * Class used to share progress information about assets loading
  99049. */
  99050. var AssetsProgressEvent = /** @class */ (function () {
  99051. /**
  99052. * Creates a {BABYLON.AssetsProgressEvent}
  99053. * @param remainingCount defines the number of remaining tasks to process
  99054. * @param totalCount defines the total number of tasks
  99055. * @param task defines the task that was just processed
  99056. */
  99057. function AssetsProgressEvent(remainingCount, totalCount, task) {
  99058. this.remainingCount = remainingCount;
  99059. this.totalCount = totalCount;
  99060. this.task = task;
  99061. }
  99062. return AssetsProgressEvent;
  99063. }());
  99064. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  99065. /**
  99066. * Define a task used by {BABYLON.AssetsManager} to load meshes
  99067. */
  99068. var MeshAssetTask = /** @class */ (function (_super) {
  99069. __extends(MeshAssetTask, _super);
  99070. /**
  99071. * Creates a new {BABYLON.MeshAssetTask}
  99072. * @param name defines the name of the task
  99073. * @param meshesNames defines the list of mesh's names you want to load
  99074. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  99075. * @param sceneFilename defines the filename of the scene to load from
  99076. */
  99077. function MeshAssetTask(
  99078. /**
  99079. * Defines the name of the task
  99080. */
  99081. name,
  99082. /**
  99083. * Defines the list of mesh's names you want to load
  99084. */
  99085. meshesNames,
  99086. /**
  99087. * Defines the root url to use as a base to load your meshes and associated resources
  99088. */
  99089. rootUrl,
  99090. /**
  99091. * Defines the filename of the scene to load from
  99092. */
  99093. sceneFilename) {
  99094. var _this = _super.call(this, name) || this;
  99095. _this.name = name;
  99096. _this.meshesNames = meshesNames;
  99097. _this.rootUrl = rootUrl;
  99098. _this.sceneFilename = sceneFilename;
  99099. return _this;
  99100. }
  99101. /**
  99102. * Execute the current task
  99103. * @param scene defines the scene where you want your assets to be loaded
  99104. * @param onSuccess is a callback called when the task is successfully executed
  99105. * @param onError is a callback called if an error occurs
  99106. */
  99107. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99108. var _this = this;
  99109. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  99110. _this.loadedMeshes = meshes;
  99111. _this.loadedParticleSystems = particleSystems;
  99112. _this.loadedSkeletons = skeletons;
  99113. onSuccess();
  99114. }, null, function (scene, message, exception) {
  99115. onError(message, exception);
  99116. });
  99117. };
  99118. return MeshAssetTask;
  99119. }(AbstractAssetTask));
  99120. BABYLON.MeshAssetTask = MeshAssetTask;
  99121. /**
  99122. * Define a task used by {BABYLON.AssetsManager} to load text content
  99123. */
  99124. var TextFileAssetTask = /** @class */ (function (_super) {
  99125. __extends(TextFileAssetTask, _super);
  99126. /**
  99127. * Creates a new TextFileAssetTask object
  99128. * @param name defines the name of the task
  99129. * @param url defines the location of the file to load
  99130. */
  99131. function TextFileAssetTask(
  99132. /**
  99133. * Defines the name of the task
  99134. */
  99135. name,
  99136. /**
  99137. * Defines the location of the file to load
  99138. */
  99139. url) {
  99140. var _this = _super.call(this, name) || this;
  99141. _this.name = name;
  99142. _this.url = url;
  99143. return _this;
  99144. }
  99145. /**
  99146. * Execute the current task
  99147. * @param scene defines the scene where you want your assets to be loaded
  99148. * @param onSuccess is a callback called when the task is successfully executed
  99149. * @param onError is a callback called if an error occurs
  99150. */
  99151. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99152. var _this = this;
  99153. scene._loadFile(this.url, function (data) {
  99154. _this.text = data;
  99155. onSuccess();
  99156. }, undefined, false, false, function (request, exception) {
  99157. if (request) {
  99158. onError(request.status + " " + request.statusText, exception);
  99159. }
  99160. });
  99161. };
  99162. return TextFileAssetTask;
  99163. }(AbstractAssetTask));
  99164. BABYLON.TextFileAssetTask = TextFileAssetTask;
  99165. /**
  99166. * Define a task used by {BABYLON.AssetsManager} to load binary data
  99167. */
  99168. var BinaryFileAssetTask = /** @class */ (function (_super) {
  99169. __extends(BinaryFileAssetTask, _super);
  99170. /**
  99171. * Creates a new BinaryFileAssetTask object
  99172. * @param name defines the name of the new task
  99173. * @param url defines the location of the file to load
  99174. */
  99175. function BinaryFileAssetTask(
  99176. /**
  99177. * Defines the name of the task
  99178. */
  99179. name,
  99180. /**
  99181. * Defines the location of the file to load
  99182. */
  99183. url) {
  99184. var _this = _super.call(this, name) || this;
  99185. _this.name = name;
  99186. _this.url = url;
  99187. return _this;
  99188. }
  99189. /**
  99190. * Execute the current task
  99191. * @param scene defines the scene where you want your assets to be loaded
  99192. * @param onSuccess is a callback called when the task is successfully executed
  99193. * @param onError is a callback called if an error occurs
  99194. */
  99195. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99196. var _this = this;
  99197. scene._loadFile(this.url, function (data) {
  99198. _this.data = data;
  99199. onSuccess();
  99200. }, undefined, true, true, function (request, exception) {
  99201. if (request) {
  99202. onError(request.status + " " + request.statusText, exception);
  99203. }
  99204. });
  99205. };
  99206. return BinaryFileAssetTask;
  99207. }(AbstractAssetTask));
  99208. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  99209. /**
  99210. * Define a task used by {BABYLON.AssetsManager} to load images
  99211. */
  99212. var ImageAssetTask = /** @class */ (function (_super) {
  99213. __extends(ImageAssetTask, _super);
  99214. /**
  99215. * Creates a new ImageAssetTask
  99216. * @param name defines the name of the task
  99217. * @param url defines the location of the image to load
  99218. */
  99219. function ImageAssetTask(
  99220. /**
  99221. * Defines the name of the task
  99222. */
  99223. name,
  99224. /**
  99225. * Defines the location of the image to load
  99226. */
  99227. url) {
  99228. var _this = _super.call(this, name) || this;
  99229. _this.name = name;
  99230. _this.url = url;
  99231. return _this;
  99232. }
  99233. /**
  99234. * Execute the current task
  99235. * @param scene defines the scene where you want your assets to be loaded
  99236. * @param onSuccess is a callback called when the task is successfully executed
  99237. * @param onError is a callback called if an error occurs
  99238. */
  99239. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99240. var _this = this;
  99241. var img = new Image();
  99242. BABYLON.Tools.SetCorsBehavior(this.url, img);
  99243. img.onload = function () {
  99244. _this.image = img;
  99245. onSuccess();
  99246. };
  99247. img.onerror = function (err) {
  99248. onError("Error loading image", err);
  99249. };
  99250. img.src = this.url;
  99251. };
  99252. return ImageAssetTask;
  99253. }(AbstractAssetTask));
  99254. BABYLON.ImageAssetTask = ImageAssetTask;
  99255. /**
  99256. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  99257. */
  99258. var TextureAssetTask = /** @class */ (function (_super) {
  99259. __extends(TextureAssetTask, _super);
  99260. /**
  99261. * Creates a new TextureAssetTask object
  99262. * @param name defines the name of the task
  99263. * @param url defines the location of the file to load
  99264. * @param noMipmap defines if mipmap should not be generated (default is false)
  99265. * @param invertY defines if texture must be inverted on Y axis (default is false)
  99266. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99267. */
  99268. function TextureAssetTask(
  99269. /**
  99270. * Defines the name of the task
  99271. */
  99272. name,
  99273. /**
  99274. * Defines the location of the file to load
  99275. */
  99276. url,
  99277. /**
  99278. * Defines if mipmap should not be generated (default is false)
  99279. */
  99280. noMipmap,
  99281. /**
  99282. * Defines if texture must be inverted on Y axis (default is false)
  99283. */
  99284. invertY,
  99285. /**
  99286. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99287. */
  99288. samplingMode) {
  99289. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99290. var _this = _super.call(this, name) || this;
  99291. _this.name = name;
  99292. _this.url = url;
  99293. _this.noMipmap = noMipmap;
  99294. _this.invertY = invertY;
  99295. _this.samplingMode = samplingMode;
  99296. return _this;
  99297. }
  99298. /**
  99299. * Execute the current task
  99300. * @param scene defines the scene where you want your assets to be loaded
  99301. * @param onSuccess is a callback called when the task is successfully executed
  99302. * @param onError is a callback called if an error occurs
  99303. */
  99304. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99305. var onload = function () {
  99306. onSuccess();
  99307. };
  99308. var onerror = function (message, exception) {
  99309. onError(message, exception);
  99310. };
  99311. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  99312. };
  99313. return TextureAssetTask;
  99314. }(AbstractAssetTask));
  99315. BABYLON.TextureAssetTask = TextureAssetTask;
  99316. /**
  99317. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  99318. */
  99319. var CubeTextureAssetTask = /** @class */ (function (_super) {
  99320. __extends(CubeTextureAssetTask, _super);
  99321. /**
  99322. * Creates a new CubeTextureAssetTask
  99323. * @param name defines the name of the task
  99324. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99325. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99326. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99327. * @param files defines the explicit list of files (undefined by default)
  99328. */
  99329. function CubeTextureAssetTask(
  99330. /**
  99331. * Defines the name of the task
  99332. */
  99333. name,
  99334. /**
  99335. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99336. */
  99337. url,
  99338. /**
  99339. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99340. */
  99341. extensions,
  99342. /**
  99343. * Defines if mipmaps should not be generated (default is false)
  99344. */
  99345. noMipmap,
  99346. /**
  99347. * Defines the explicit list of files (undefined by default)
  99348. */
  99349. files) {
  99350. var _this = _super.call(this, name) || this;
  99351. _this.name = name;
  99352. _this.url = url;
  99353. _this.extensions = extensions;
  99354. _this.noMipmap = noMipmap;
  99355. _this.files = files;
  99356. return _this;
  99357. }
  99358. /**
  99359. * Execute the current task
  99360. * @param scene defines the scene where you want your assets to be loaded
  99361. * @param onSuccess is a callback called when the task is successfully executed
  99362. * @param onError is a callback called if an error occurs
  99363. */
  99364. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99365. var onload = function () {
  99366. onSuccess();
  99367. };
  99368. var onerror = function (message, exception) {
  99369. onError(message, exception);
  99370. };
  99371. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  99372. };
  99373. return CubeTextureAssetTask;
  99374. }(AbstractAssetTask));
  99375. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  99376. /**
  99377. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  99378. */
  99379. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  99380. __extends(HDRCubeTextureAssetTask, _super);
  99381. /**
  99382. * Creates a new HDRCubeTextureAssetTask object
  99383. * @param name defines the name of the task
  99384. * @param url defines the location of the file to load
  99385. * @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.
  99386. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99387. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99388. * @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)
  99389. * @param reserved Internal use only
  99390. */
  99391. function HDRCubeTextureAssetTask(
  99392. /**
  99393. * Defines the name of the task
  99394. */
  99395. name,
  99396. /**
  99397. * Defines the location of the file to load
  99398. */
  99399. url,
  99400. /**
  99401. * Defines the desired size (the more it increases the longer the generation will be)
  99402. */
  99403. size,
  99404. /**
  99405. * Defines if mipmaps should not be generated (default is false)
  99406. */
  99407. noMipmap,
  99408. /**
  99409. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99410. */
  99411. generateHarmonics,
  99412. /**
  99413. * 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)
  99414. */
  99415. gammaSpace,
  99416. /**
  99417. * Internal Use Only
  99418. */
  99419. reserved) {
  99420. if (noMipmap === void 0) { noMipmap = false; }
  99421. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99422. if (gammaSpace === void 0) { gammaSpace = false; }
  99423. if (reserved === void 0) { reserved = false; }
  99424. var _this = _super.call(this, name) || this;
  99425. _this.name = name;
  99426. _this.url = url;
  99427. _this.size = size;
  99428. _this.noMipmap = noMipmap;
  99429. _this.generateHarmonics = generateHarmonics;
  99430. _this.gammaSpace = gammaSpace;
  99431. _this.reserved = reserved;
  99432. return _this;
  99433. }
  99434. /**
  99435. * Execute the current task
  99436. * @param scene defines the scene where you want your assets to be loaded
  99437. * @param onSuccess is a callback called when the task is successfully executed
  99438. * @param onError is a callback called if an error occurs
  99439. */
  99440. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  99441. var onload = function () {
  99442. onSuccess();
  99443. };
  99444. var onerror = function (message, exception) {
  99445. onError(message, exception);
  99446. };
  99447. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  99448. };
  99449. return HDRCubeTextureAssetTask;
  99450. }(AbstractAssetTask));
  99451. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  99452. /**
  99453. * This class can be used to easily import assets into a scene
  99454. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  99455. */
  99456. var AssetsManager = /** @class */ (function () {
  99457. /**
  99458. * Creates a new AssetsManager
  99459. * @param scene defines the scene to work on
  99460. */
  99461. function AssetsManager(scene) {
  99462. this._isLoading = false;
  99463. this._tasks = new Array();
  99464. this._waitingTasksCount = 0;
  99465. this._totalTasksCount = 0;
  99466. /**
  99467. * Observable called when all tasks are processed
  99468. */
  99469. this.onTaskSuccessObservable = new BABYLON.Observable();
  99470. /**
  99471. * Observable called when a task had an error
  99472. */
  99473. this.onTaskErrorObservable = new BABYLON.Observable();
  99474. /**
  99475. * Observable called when a task is successful
  99476. */
  99477. this.onTasksDoneObservable = new BABYLON.Observable();
  99478. /**
  99479. * Observable called when a task is done (whatever the result is)
  99480. */
  99481. this.onProgressObservable = new BABYLON.Observable();
  99482. /**
  99483. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  99484. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  99485. */
  99486. this.useDefaultLoadingScreen = true;
  99487. this._scene = scene;
  99488. }
  99489. /**
  99490. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  99491. * @param taskName defines the name of the new task
  99492. * @param meshesNames defines the name of meshes to load
  99493. * @param rootUrl defines the root url to use to locate files
  99494. * @param sceneFilename defines the filename of the scene file
  99495. * @returns a new {BABYLON.MeshAssetTask} object
  99496. */
  99497. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  99498. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  99499. this._tasks.push(task);
  99500. return task;
  99501. };
  99502. /**
  99503. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  99504. * @param taskName defines the name of the new task
  99505. * @param url defines the url of the file to load
  99506. * @returns a new {BABYLON.TextFileAssetTask} object
  99507. */
  99508. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  99509. var task = new TextFileAssetTask(taskName, url);
  99510. this._tasks.push(task);
  99511. return task;
  99512. };
  99513. /**
  99514. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  99515. * @param taskName defines the name of the new task
  99516. * @param url defines the url of the file to load
  99517. * @returns a new {BABYLON.BinaryFileAssetTask} object
  99518. */
  99519. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  99520. var task = new BinaryFileAssetTask(taskName, url);
  99521. this._tasks.push(task);
  99522. return task;
  99523. };
  99524. /**
  99525. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  99526. * @param taskName defines the name of the new task
  99527. * @param url defines the url of the file to load
  99528. * @returns a new {BABYLON.ImageAssetTask} object
  99529. */
  99530. AssetsManager.prototype.addImageTask = function (taskName, url) {
  99531. var task = new ImageAssetTask(taskName, url);
  99532. this._tasks.push(task);
  99533. return task;
  99534. };
  99535. /**
  99536. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  99537. * @param taskName defines the name of the new task
  99538. * @param url defines the url of the file to load
  99539. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99540. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  99541. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  99542. * @returns a new {BABYLON.TextureAssetTask} object
  99543. */
  99544. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  99545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99546. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  99547. this._tasks.push(task);
  99548. return task;
  99549. };
  99550. /**
  99551. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  99552. * @param taskName defines the name of the new task
  99553. * @param url defines the url of the file to load
  99554. * @param extensions defines the extension to use to load the cube map (can be null)
  99555. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99556. * @param files defines the list of files to load (can be null)
  99557. * @returns a new {BABYLON.CubeTextureAssetTask} object
  99558. */
  99559. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  99560. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  99561. this._tasks.push(task);
  99562. return task;
  99563. };
  99564. /**
  99565. *
  99566. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  99567. * @param taskName defines the name of the new task
  99568. * @param url defines the url of the file to load
  99569. * @param size defines the size you want for the cubemap (can be null)
  99570. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99571. * @param generateHarmonics defines if you want to automatically generate (true by default)
  99572. * @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)
  99573. * @param reserved Internal use only
  99574. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  99575. */
  99576. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  99577. if (noMipmap === void 0) { noMipmap = false; }
  99578. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99579. if (gammaSpace === void 0) { gammaSpace = false; }
  99580. if (reserved === void 0) { reserved = false; }
  99581. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  99582. this._tasks.push(task);
  99583. return task;
  99584. };
  99585. /**
  99586. * Remove a task from the assets manager.
  99587. * @param task the task to remove
  99588. */
  99589. AssetsManager.prototype.removeTask = function (task) {
  99590. var index = this._tasks.indexOf(task);
  99591. if (index > -1) {
  99592. this._tasks.splice(index, 1);
  99593. }
  99594. };
  99595. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  99596. this._waitingTasksCount--;
  99597. try {
  99598. if (this.onProgress) {
  99599. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  99600. }
  99601. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  99602. }
  99603. catch (e) {
  99604. BABYLON.Tools.Error("Error running progress callbacks.");
  99605. console.log(e);
  99606. }
  99607. if (this._waitingTasksCount === 0) {
  99608. try {
  99609. if (this.onFinish) {
  99610. this.onFinish(this._tasks);
  99611. }
  99612. // Let's remove successfull tasks
  99613. var currentTasks = this._tasks.slice();
  99614. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  99615. var task = currentTasks_1[_i];
  99616. if (task.taskState === AssetTaskState.DONE) {
  99617. var index = this._tasks.indexOf(task);
  99618. if (index > -1) {
  99619. this._tasks.splice(index, 1);
  99620. }
  99621. }
  99622. }
  99623. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99624. }
  99625. catch (e) {
  99626. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  99627. console.log(e);
  99628. }
  99629. this._isLoading = false;
  99630. this._scene.getEngine().hideLoadingUI();
  99631. }
  99632. };
  99633. AssetsManager.prototype._runTask = function (task) {
  99634. var _this = this;
  99635. var done = function () {
  99636. try {
  99637. if (_this.onTaskSuccess) {
  99638. _this.onTaskSuccess(task);
  99639. }
  99640. _this.onTaskSuccessObservable.notifyObservers(task);
  99641. _this._decreaseWaitingTasksCount(task);
  99642. }
  99643. catch (e) {
  99644. error("Error executing task success callbacks", e);
  99645. }
  99646. };
  99647. var error = function (message, exception) {
  99648. task._setErrorObject(message, exception);
  99649. if (_this.onTaskError) {
  99650. _this.onTaskError(task);
  99651. }
  99652. _this.onTaskErrorObservable.notifyObservers(task);
  99653. _this._decreaseWaitingTasksCount(task);
  99654. };
  99655. task.run(this._scene, done, error);
  99656. };
  99657. /**
  99658. * Reset the {BABYLON.AssetsManager} and remove all tasks
  99659. * @return the current instance of the {BABYLON.AssetsManager}
  99660. */
  99661. AssetsManager.prototype.reset = function () {
  99662. this._isLoading = false;
  99663. this._tasks = new Array();
  99664. return this;
  99665. };
  99666. /**
  99667. * Start the loading process
  99668. * @return the current instance of the {BABYLON.AssetsManager}
  99669. */
  99670. AssetsManager.prototype.load = function () {
  99671. if (this._isLoading) {
  99672. return this;
  99673. }
  99674. this._isLoading = true;
  99675. this._waitingTasksCount = this._tasks.length;
  99676. this._totalTasksCount = this._tasks.length;
  99677. if (this._waitingTasksCount === 0) {
  99678. this._isLoading = false;
  99679. if (this.onFinish) {
  99680. this.onFinish(this._tasks);
  99681. }
  99682. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99683. return this;
  99684. }
  99685. if (this.useDefaultLoadingScreen) {
  99686. this._scene.getEngine().displayLoadingUI();
  99687. }
  99688. for (var index = 0; index < this._tasks.length; index++) {
  99689. var task = this._tasks[index];
  99690. if (task.taskState === AssetTaskState.INIT) {
  99691. this._runTask(task);
  99692. }
  99693. }
  99694. return this;
  99695. };
  99696. return AssetsManager;
  99697. }());
  99698. BABYLON.AssetsManager = AssetsManager;
  99699. })(BABYLON || (BABYLON = {}));
  99700. //# sourceMappingURL=babylon.assetsManager.js.map
  99701. var BABYLON;
  99702. (function (BABYLON) {
  99703. var serializedGeometries = [];
  99704. var serializeGeometry = function (geometry, serializationGeometries) {
  99705. if (serializedGeometries[geometry.id]) {
  99706. return;
  99707. }
  99708. if (geometry.doNotSerialize) {
  99709. return;
  99710. }
  99711. if (geometry instanceof BABYLON.BoxGeometry) {
  99712. serializationGeometries.boxes.push(geometry.serialize());
  99713. }
  99714. else if (geometry instanceof BABYLON.SphereGeometry) {
  99715. serializationGeometries.spheres.push(geometry.serialize());
  99716. }
  99717. else if (geometry instanceof BABYLON.CylinderGeometry) {
  99718. serializationGeometries.cylinders.push(geometry.serialize());
  99719. }
  99720. else if (geometry instanceof BABYLON.TorusGeometry) {
  99721. serializationGeometries.toruses.push(geometry.serialize());
  99722. }
  99723. else if (geometry instanceof BABYLON.GroundGeometry) {
  99724. serializationGeometries.grounds.push(geometry.serialize());
  99725. }
  99726. else if (geometry instanceof BABYLON.Plane) {
  99727. serializationGeometries.planes.push(geometry.serialize());
  99728. }
  99729. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  99730. serializationGeometries.torusKnots.push(geometry.serialize());
  99731. }
  99732. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  99733. throw new Error("Unknown primitive type");
  99734. }
  99735. else {
  99736. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  99737. }
  99738. serializedGeometries[geometry.id] = true;
  99739. };
  99740. var serializeMesh = function (mesh, serializationScene) {
  99741. var serializationObject = {};
  99742. // Geometry
  99743. var geometry = mesh._geometry;
  99744. if (geometry) {
  99745. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  99746. // 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
  99747. serializeGeometry(geometry, serializationScene.geometries);
  99748. }
  99749. }
  99750. // Custom
  99751. if (mesh.serialize) {
  99752. mesh.serialize(serializationObject);
  99753. }
  99754. return serializationObject;
  99755. };
  99756. var finalizeSingleMesh = function (mesh, serializationObject) {
  99757. //only works if the mesh is already loaded
  99758. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99759. //serialize material
  99760. if (mesh.material) {
  99761. if (mesh.material instanceof BABYLON.MultiMaterial) {
  99762. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  99763. serializationObject.materials = serializationObject.materials || [];
  99764. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99765. serializationObject.multiMaterials.push(mesh.material.serialize());
  99766. var _loop_1 = function (submaterial) {
  99767. if (submaterial) {
  99768. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  99769. serializationObject.materials.push(submaterial.serialize());
  99770. }
  99771. }
  99772. };
  99773. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  99774. var submaterial = _a[_i];
  99775. _loop_1(submaterial);
  99776. }
  99777. }
  99778. }
  99779. else {
  99780. serializationObject.materials = serializationObject.materials || [];
  99781. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99782. serializationObject.materials.push(mesh.material.serialize());
  99783. }
  99784. }
  99785. }
  99786. //serialize geometry
  99787. var geometry = mesh._geometry;
  99788. if (geometry) {
  99789. if (!serializationObject.geometries) {
  99790. serializationObject.geometries = {};
  99791. serializationObject.geometries.boxes = [];
  99792. serializationObject.geometries.spheres = [];
  99793. serializationObject.geometries.cylinders = [];
  99794. serializationObject.geometries.toruses = [];
  99795. serializationObject.geometries.grounds = [];
  99796. serializationObject.geometries.planes = [];
  99797. serializationObject.geometries.torusKnots = [];
  99798. serializationObject.geometries.vertexData = [];
  99799. }
  99800. serializeGeometry(geometry, serializationObject.geometries);
  99801. }
  99802. // Skeletons
  99803. if (mesh.skeleton) {
  99804. serializationObject.skeletons = serializationObject.skeletons || [];
  99805. serializationObject.skeletons.push(mesh.skeleton.serialize());
  99806. }
  99807. //serialize the actual mesh
  99808. serializationObject.meshes = serializationObject.meshes || [];
  99809. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99810. }
  99811. };
  99812. var SceneSerializer = /** @class */ (function () {
  99813. function SceneSerializer() {
  99814. }
  99815. SceneSerializer.ClearCache = function () {
  99816. serializedGeometries = [];
  99817. };
  99818. SceneSerializer.Serialize = function (scene) {
  99819. var serializationObject = {};
  99820. SceneSerializer.ClearCache();
  99821. // Scene
  99822. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  99823. serializationObject.autoClear = scene.autoClear;
  99824. serializationObject.clearColor = scene.clearColor.asArray();
  99825. serializationObject.ambientColor = scene.ambientColor.asArray();
  99826. serializationObject.gravity = scene.gravity.asArray();
  99827. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  99828. serializationObject.workerCollisions = scene.workerCollisions;
  99829. // Fog
  99830. if (scene.fogMode && scene.fogMode !== 0) {
  99831. serializationObject.fogMode = scene.fogMode;
  99832. serializationObject.fogColor = scene.fogColor.asArray();
  99833. serializationObject.fogStart = scene.fogStart;
  99834. serializationObject.fogEnd = scene.fogEnd;
  99835. serializationObject.fogDensity = scene.fogDensity;
  99836. }
  99837. //Physics
  99838. if (scene.isPhysicsEnabled()) {
  99839. var physicEngine = scene.getPhysicsEngine();
  99840. if (physicEngine) {
  99841. serializationObject.physicsEnabled = true;
  99842. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  99843. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  99844. }
  99845. }
  99846. // Metadata
  99847. if (scene.metadata) {
  99848. serializationObject.metadata = scene.metadata;
  99849. }
  99850. // Morph targets
  99851. serializationObject.morphTargetManagers = [];
  99852. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  99853. var abstractMesh = _a[_i];
  99854. var manager = abstractMesh.morphTargetManager;
  99855. if (manager) {
  99856. serializationObject.morphTargetManagers.push(manager.serialize());
  99857. }
  99858. }
  99859. // Lights
  99860. serializationObject.lights = [];
  99861. var index;
  99862. var light;
  99863. for (index = 0; index < scene.lights.length; index++) {
  99864. light = scene.lights[index];
  99865. if (!light.doNotSerialize) {
  99866. serializationObject.lights.push(light.serialize());
  99867. }
  99868. }
  99869. // Cameras
  99870. serializationObject.cameras = [];
  99871. for (index = 0; index < scene.cameras.length; index++) {
  99872. var camera = scene.cameras[index];
  99873. if (!camera.doNotSerialize) {
  99874. serializationObject.cameras.push(camera.serialize());
  99875. }
  99876. }
  99877. if (scene.activeCamera) {
  99878. serializationObject.activeCameraID = scene.activeCamera.id;
  99879. }
  99880. // Animations
  99881. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  99882. // Materials
  99883. serializationObject.materials = [];
  99884. serializationObject.multiMaterials = [];
  99885. var material;
  99886. for (index = 0; index < scene.materials.length; index++) {
  99887. material = scene.materials[index];
  99888. if (!material.doNotSerialize) {
  99889. serializationObject.materials.push(material.serialize());
  99890. }
  99891. }
  99892. // MultiMaterials
  99893. serializationObject.multiMaterials = [];
  99894. for (index = 0; index < scene.multiMaterials.length; index++) {
  99895. var multiMaterial = scene.multiMaterials[index];
  99896. serializationObject.multiMaterials.push(multiMaterial.serialize());
  99897. }
  99898. // Environment texture
  99899. if (scene.environmentTexture) {
  99900. serializationObject.environmentTexture = scene.environmentTexture.name;
  99901. }
  99902. // Skeletons
  99903. serializationObject.skeletons = [];
  99904. for (index = 0; index < scene.skeletons.length; index++) {
  99905. var skeleton = scene.skeletons[index];
  99906. if (!skeleton.doNotSerialize) {
  99907. serializationObject.skeletons.push(skeleton.serialize());
  99908. }
  99909. }
  99910. // Transform nodes
  99911. serializationObject.transformNodes = [];
  99912. for (index = 0; index < scene.transformNodes.length; index++) {
  99913. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  99914. }
  99915. // Geometries
  99916. serializationObject.geometries = {};
  99917. serializationObject.geometries.boxes = [];
  99918. serializationObject.geometries.spheres = [];
  99919. serializationObject.geometries.cylinders = [];
  99920. serializationObject.geometries.toruses = [];
  99921. serializationObject.geometries.grounds = [];
  99922. serializationObject.geometries.planes = [];
  99923. serializationObject.geometries.torusKnots = [];
  99924. serializationObject.geometries.vertexData = [];
  99925. serializedGeometries = [];
  99926. var geometries = scene.getGeometries();
  99927. for (index = 0; index < geometries.length; index++) {
  99928. var geometry = geometries[index];
  99929. if (geometry.isReady()) {
  99930. serializeGeometry(geometry, serializationObject.geometries);
  99931. }
  99932. }
  99933. // Meshes
  99934. serializationObject.meshes = [];
  99935. for (index = 0; index < scene.meshes.length; index++) {
  99936. var abstractMesh = scene.meshes[index];
  99937. if (abstractMesh instanceof BABYLON.Mesh) {
  99938. var mesh = abstractMesh;
  99939. if (!mesh.doNotSerialize) {
  99940. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99941. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99942. }
  99943. }
  99944. }
  99945. }
  99946. // Particles Systems
  99947. serializationObject.particleSystems = [];
  99948. for (index = 0; index < scene.particleSystems.length; index++) {
  99949. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  99950. }
  99951. // Shadows
  99952. serializationObject.shadowGenerators = [];
  99953. for (index = 0; index < scene.lights.length; index++) {
  99954. light = scene.lights[index];
  99955. var shadowGenerator = light.getShadowGenerator();
  99956. if (shadowGenerator) {
  99957. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  99958. }
  99959. }
  99960. // Action Manager
  99961. if (scene.actionManager) {
  99962. serializationObject.actions = scene.actionManager.serialize("scene");
  99963. }
  99964. // Audio
  99965. serializationObject.sounds = [];
  99966. for (index = 0; index < scene.soundTracks.length; index++) {
  99967. var soundtrack = scene.soundTracks[index];
  99968. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  99969. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  99970. }
  99971. }
  99972. // Components
  99973. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  99974. var component = _c[_b];
  99975. component.serialize(serializationObject);
  99976. }
  99977. return serializationObject;
  99978. };
  99979. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  99980. if (withParents === void 0) { withParents = false; }
  99981. if (withChildren === void 0) { withChildren = false; }
  99982. var serializationObject = {};
  99983. SceneSerializer.ClearCache();
  99984. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  99985. if (withParents || withChildren) {
  99986. //deliberate for loop! not for each, appended should be processed as well.
  99987. for (var i = 0; i < toSerialize.length; ++i) {
  99988. if (withChildren) {
  99989. toSerialize[i].getDescendants().forEach(function (node) {
  99990. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  99991. toSerialize.push(node);
  99992. }
  99993. });
  99994. }
  99995. //make sure the array doesn't contain the object already
  99996. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  99997. toSerialize.push(toSerialize[i].parent);
  99998. }
  99999. }
  100000. }
  100001. toSerialize.forEach(function (mesh) {
  100002. finalizeSingleMesh(mesh, serializationObject);
  100003. });
  100004. return serializationObject;
  100005. };
  100006. return SceneSerializer;
  100007. }());
  100008. BABYLON.SceneSerializer = SceneSerializer;
  100009. })(BABYLON || (BABYLON = {}));
  100010. //# sourceMappingURL=babylon.sceneSerializer.js.map
  100011. var BABYLON;
  100012. (function (BABYLON) {
  100013. var ReflectionProbe = /** @class */ (function () {
  100014. function ReflectionProbe(name, size, scene, generateMipMaps) {
  100015. if (generateMipMaps === void 0) { generateMipMaps = true; }
  100016. var _this = this;
  100017. this.name = name;
  100018. this._viewMatrix = BABYLON.Matrix.Identity();
  100019. this._target = BABYLON.Vector3.Zero();
  100020. this._add = BABYLON.Vector3.Zero();
  100021. this._invertYAxis = false;
  100022. this.position = BABYLON.Vector3.Zero();
  100023. this._scene = scene;
  100024. this._scene.reflectionProbes.push(this);
  100025. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  100026. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  100027. switch (faceIndex) {
  100028. case 0:
  100029. _this._add.copyFromFloats(1, 0, 0);
  100030. break;
  100031. case 1:
  100032. _this._add.copyFromFloats(-1, 0, 0);
  100033. break;
  100034. case 2:
  100035. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  100036. break;
  100037. case 3:
  100038. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  100039. break;
  100040. case 4:
  100041. _this._add.copyFromFloats(0, 0, 1);
  100042. break;
  100043. case 5:
  100044. _this._add.copyFromFloats(0, 0, -1);
  100045. break;
  100046. }
  100047. if (_this._attachedMesh) {
  100048. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  100049. }
  100050. _this.position.addToRef(_this._add, _this._target);
  100051. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  100052. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  100053. scene._forcedViewPosition = _this.position;
  100054. });
  100055. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  100056. scene._forcedViewPosition = null;
  100057. scene.updateTransformMatrix(true);
  100058. });
  100059. if (scene.activeCamera) {
  100060. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  100061. }
  100062. }
  100063. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  100064. get: function () {
  100065. return this._renderTargetTexture.samples;
  100066. },
  100067. set: function (value) {
  100068. this._renderTargetTexture.samples = value;
  100069. },
  100070. enumerable: true,
  100071. configurable: true
  100072. });
  100073. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  100074. get: function () {
  100075. return this._renderTargetTexture.refreshRate;
  100076. },
  100077. set: function (value) {
  100078. this._renderTargetTexture.refreshRate = value;
  100079. },
  100080. enumerable: true,
  100081. configurable: true
  100082. });
  100083. ReflectionProbe.prototype.getScene = function () {
  100084. return this._scene;
  100085. };
  100086. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  100087. get: function () {
  100088. return this._renderTargetTexture;
  100089. },
  100090. enumerable: true,
  100091. configurable: true
  100092. });
  100093. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  100094. get: function () {
  100095. return this._renderTargetTexture.renderList;
  100096. },
  100097. enumerable: true,
  100098. configurable: true
  100099. });
  100100. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  100101. this._attachedMesh = mesh;
  100102. };
  100103. /**
  100104. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  100105. *
  100106. * @param renderingGroupId The rendering group id corresponding to its index
  100107. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  100108. */
  100109. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  100110. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  100111. };
  100112. ReflectionProbe.prototype.dispose = function () {
  100113. var index = this._scene.reflectionProbes.indexOf(this);
  100114. if (index !== -1) {
  100115. // Remove from the scene if found
  100116. this._scene.reflectionProbes.splice(index, 1);
  100117. }
  100118. if (this._renderTargetTexture) {
  100119. this._renderTargetTexture.dispose();
  100120. this._renderTargetTexture = null;
  100121. }
  100122. };
  100123. return ReflectionProbe;
  100124. }());
  100125. BABYLON.ReflectionProbe = ReflectionProbe;
  100126. })(BABYLON || (BABYLON = {}));
  100127. //# sourceMappingURL=babylon.reflectionProbe.js.map
  100128. var BABYLON;
  100129. (function (BABYLON) {
  100130. /**
  100131. * Defines the layer scene component responsible to manage any layers
  100132. * in a given scene.
  100133. */
  100134. var LayerSceneComponent = /** @class */ (function () {
  100135. /**
  100136. * Creates a new instance of the component for the given scene
  100137. * @param scene Defines the scene to register the component in
  100138. */
  100139. function LayerSceneComponent(scene) {
  100140. /**
  100141. * The component name helpfull to identify the component in the list of scene components.
  100142. */
  100143. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  100144. this.scene = scene;
  100145. this._engine = scene.getEngine();
  100146. scene.layers = new Array();
  100147. }
  100148. /**
  100149. * Registers the component in a given scene
  100150. */
  100151. LayerSceneComponent.prototype.register = function () {
  100152. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  100153. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  100154. };
  100155. /**
  100156. * Rebuilds the elements related to this component in case of
  100157. * context lost for instance.
  100158. */
  100159. LayerSceneComponent.prototype.rebuild = function () {
  100160. var layers = this.scene.layers;
  100161. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  100162. var layer = layers_1[_i];
  100163. layer._rebuild();
  100164. }
  100165. };
  100166. /**
  100167. * Disposes the component and the associated ressources.
  100168. */
  100169. LayerSceneComponent.prototype.dispose = function () {
  100170. var layers = this.scene.layers;
  100171. while (layers.length) {
  100172. layers[0].dispose();
  100173. }
  100174. };
  100175. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  100176. var layers = this.scene.layers;
  100177. if (layers.length) {
  100178. this._engine.setDepthBuffer(false);
  100179. var cameraLayerMask = camera.layerMask;
  100180. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  100181. var layer = layers_2[_i];
  100182. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  100183. layer.render();
  100184. }
  100185. }
  100186. this._engine.setDepthBuffer(true);
  100187. }
  100188. };
  100189. LayerSceneComponent.prototype._drawBackground = function (camera) {
  100190. this._draw(camera, true);
  100191. };
  100192. LayerSceneComponent.prototype._drawForeground = function (camera) {
  100193. this._draw(camera, false);
  100194. };
  100195. return LayerSceneComponent;
  100196. }());
  100197. BABYLON.LayerSceneComponent = LayerSceneComponent;
  100198. })(BABYLON || (BABYLON = {}));
  100199. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  100200. var BABYLON;
  100201. (function (BABYLON) {
  100202. var Layer = /** @class */ (function () {
  100203. function Layer(name, imgUrl, scene, isBackground, color) {
  100204. this.name = name;
  100205. this.scale = new BABYLON.Vector2(1, 1);
  100206. this.offset = new BABYLON.Vector2(0, 0);
  100207. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  100208. this.layerMask = 0x0FFFFFFF;
  100209. this._vertexBuffers = {};
  100210. // Events
  100211. /**
  100212. * An event triggered when the layer is disposed.
  100213. */
  100214. this.onDisposeObservable = new BABYLON.Observable();
  100215. /**
  100216. * An event triggered before rendering the scene
  100217. */
  100218. this.onBeforeRenderObservable = new BABYLON.Observable();
  100219. /**
  100220. * An event triggered after rendering the scene
  100221. */
  100222. this.onAfterRenderObservable = new BABYLON.Observable();
  100223. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  100224. this.isBackground = isBackground === undefined ? true : isBackground;
  100225. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  100226. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  100227. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  100228. if (!layerComponent) {
  100229. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  100230. this._scene._addComponent(layerComponent);
  100231. }
  100232. this._scene.layers.push(this);
  100233. var engine = this._scene.getEngine();
  100234. // VBO
  100235. var vertices = [];
  100236. vertices.push(1, 1);
  100237. vertices.push(-1, 1);
  100238. vertices.push(-1, -1);
  100239. vertices.push(1, -1);
  100240. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100241. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100242. this._createIndexBuffer();
  100243. // Effects
  100244. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  100245. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  100246. }
  100247. Object.defineProperty(Layer.prototype, "onDispose", {
  100248. set: function (callback) {
  100249. if (this._onDisposeObserver) {
  100250. this.onDisposeObservable.remove(this._onDisposeObserver);
  100251. }
  100252. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100253. },
  100254. enumerable: true,
  100255. configurable: true
  100256. });
  100257. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  100258. set: function (callback) {
  100259. if (this._onBeforeRenderObserver) {
  100260. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  100261. }
  100262. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  100263. },
  100264. enumerable: true,
  100265. configurable: true
  100266. });
  100267. Object.defineProperty(Layer.prototype, "onAfterRender", {
  100268. set: function (callback) {
  100269. if (this._onAfterRenderObserver) {
  100270. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100271. }
  100272. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  100273. },
  100274. enumerable: true,
  100275. configurable: true
  100276. });
  100277. Layer.prototype._createIndexBuffer = function () {
  100278. var engine = this._scene.getEngine();
  100279. // Indices
  100280. var indices = [];
  100281. indices.push(0);
  100282. indices.push(1);
  100283. indices.push(2);
  100284. indices.push(0);
  100285. indices.push(2);
  100286. indices.push(3);
  100287. this._indexBuffer = engine.createIndexBuffer(indices);
  100288. };
  100289. Layer.prototype._rebuild = function () {
  100290. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100291. if (vb) {
  100292. vb._rebuild();
  100293. }
  100294. this._createIndexBuffer();
  100295. };
  100296. Layer.prototype.render = function () {
  100297. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  100298. // Check
  100299. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  100300. return;
  100301. var engine = this._scene.getEngine();
  100302. this.onBeforeRenderObservable.notifyObservers(this);
  100303. // Render
  100304. engine.enableEffect(currentEffect);
  100305. engine.setState(false);
  100306. // Texture
  100307. currentEffect.setTexture("textureSampler", this.texture);
  100308. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  100309. // Color
  100310. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  100311. // Scale / offset
  100312. currentEffect.setVector2("offset", this.offset);
  100313. currentEffect.setVector2("scale", this.scale);
  100314. // VBOs
  100315. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100316. // Draw order
  100317. if (!this.alphaTest) {
  100318. engine.setAlphaMode(this.alphaBlendingMode);
  100319. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100320. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  100321. }
  100322. else {
  100323. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100324. }
  100325. this.onAfterRenderObservable.notifyObservers(this);
  100326. };
  100327. Layer.prototype.dispose = function () {
  100328. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100329. if (vertexBuffer) {
  100330. vertexBuffer.dispose();
  100331. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100332. }
  100333. if (this._indexBuffer) {
  100334. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100335. this._indexBuffer = null;
  100336. }
  100337. if (this.texture) {
  100338. this.texture.dispose();
  100339. this.texture = null;
  100340. }
  100341. // Remove from scene
  100342. var index = this._scene.layers.indexOf(this);
  100343. this._scene.layers.splice(index, 1);
  100344. // Callback
  100345. this.onDisposeObservable.notifyObservers(this);
  100346. this.onDisposeObservable.clear();
  100347. this.onAfterRenderObservable.clear();
  100348. this.onBeforeRenderObservable.clear();
  100349. };
  100350. return Layer;
  100351. }());
  100352. BABYLON.Layer = Layer;
  100353. })(BABYLON || (BABYLON = {}));
  100354. //# sourceMappingURL=babylon.layer.js.map
  100355. var BABYLON;
  100356. (function (BABYLON) {
  100357. var TextureTools = /** @class */ (function () {
  100358. function TextureTools() {
  100359. }
  100360. /**
  100361. * Uses the GPU to create a copy texture rescaled at a given size
  100362. * @param texture Texture to copy from
  100363. * @param width Desired width
  100364. * @param height Desired height
  100365. * @return Generated texture
  100366. */
  100367. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  100368. if (useBilinearMode === void 0) { useBilinearMode = true; }
  100369. var scene = texture.getScene();
  100370. var engine = scene.getEngine();
  100371. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  100372. rtt.wrapU = texture.wrapU;
  100373. rtt.wrapV = texture.wrapV;
  100374. rtt.uOffset = texture.uOffset;
  100375. rtt.vOffset = texture.vOffset;
  100376. rtt.uScale = texture.uScale;
  100377. rtt.vScale = texture.vScale;
  100378. rtt.uAng = texture.uAng;
  100379. rtt.vAng = texture.vAng;
  100380. rtt.wAng = texture.wAng;
  100381. rtt.coordinatesIndex = texture.coordinatesIndex;
  100382. rtt.level = texture.level;
  100383. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  100384. rtt._texture.isReady = false;
  100385. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100386. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100387. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100388. passPostProcess.getEffect().executeWhenCompiled(function () {
  100389. passPostProcess.onApply = function (effect) {
  100390. effect.setTexture("textureSampler", texture);
  100391. };
  100392. var internalTexture = rtt.getInternalTexture();
  100393. if (internalTexture) {
  100394. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  100395. engine.unBindFramebuffer(internalTexture);
  100396. rtt.disposeFramebufferObjects();
  100397. passPostProcess.dispose();
  100398. internalTexture.isReady = true;
  100399. }
  100400. });
  100401. return rtt;
  100402. };
  100403. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  100404. if (!scene._environmentBRDFTexture) {
  100405. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100406. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100407. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100408. scene._environmentBRDFTexture = texture;
  100409. }
  100410. return scene._environmentBRDFTexture;
  100411. };
  100412. 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=";
  100413. return TextureTools;
  100414. }());
  100415. BABYLON.TextureTools = TextureTools;
  100416. })(BABYLON || (BABYLON = {}));
  100417. //# sourceMappingURL=babylon.textureTools.js.map
  100418. var BABYLON;
  100419. (function (BABYLON) {
  100420. var FramingBehavior = /** @class */ (function () {
  100421. function FramingBehavior() {
  100422. this._mode = FramingBehavior.FitFrustumSidesMode;
  100423. this._radiusScale = 1.0;
  100424. this._positionScale = 0.5;
  100425. this._defaultElevation = 0.3;
  100426. this._elevationReturnTime = 1500;
  100427. this._elevationReturnWaitTime = 1000;
  100428. this._zoomStopsAnimation = false;
  100429. this._framingTime = 1500;
  100430. this._isPointerDown = false;
  100431. this._lastInteractionTime = -Infinity;
  100432. // Framing control
  100433. this._animatables = new Array();
  100434. this._betaIsAnimating = false;
  100435. }
  100436. Object.defineProperty(FramingBehavior.prototype, "name", {
  100437. get: function () {
  100438. return "Framing";
  100439. },
  100440. enumerable: true,
  100441. configurable: true
  100442. });
  100443. Object.defineProperty(FramingBehavior.prototype, "mode", {
  100444. /**
  100445. * Gets current mode used by the behavior.
  100446. */
  100447. get: function () {
  100448. return this._mode;
  100449. },
  100450. /**
  100451. * Sets the current mode used by the behavior
  100452. */
  100453. set: function (mode) {
  100454. this._mode = mode;
  100455. },
  100456. enumerable: true,
  100457. configurable: true
  100458. });
  100459. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  100460. /**
  100461. * Gets the scale applied to the radius
  100462. */
  100463. get: function () {
  100464. return this._radiusScale;
  100465. },
  100466. /**
  100467. * Sets the scale applied to the radius (1 by default)
  100468. */
  100469. set: function (radius) {
  100470. this._radiusScale = radius;
  100471. },
  100472. enumerable: true,
  100473. configurable: true
  100474. });
  100475. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  100476. /**
  100477. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100478. */
  100479. get: function () {
  100480. return this._positionScale;
  100481. },
  100482. /**
  100483. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100484. */
  100485. set: function (scale) {
  100486. this._positionScale = scale;
  100487. },
  100488. enumerable: true,
  100489. configurable: true
  100490. });
  100491. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  100492. /**
  100493. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100494. * behaviour is triggered, in radians.
  100495. */
  100496. get: function () {
  100497. return this._defaultElevation;
  100498. },
  100499. /**
  100500. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100501. * behaviour is triggered, in radians.
  100502. */
  100503. set: function (elevation) {
  100504. this._defaultElevation = elevation;
  100505. },
  100506. enumerable: true,
  100507. configurable: true
  100508. });
  100509. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  100510. /**
  100511. * Gets the time (in milliseconds) taken to return to the default beta position.
  100512. * Negative value indicates camera should not return to default.
  100513. */
  100514. get: function () {
  100515. return this._elevationReturnTime;
  100516. },
  100517. /**
  100518. * Sets the time (in milliseconds) taken to return to the default beta position.
  100519. * Negative value indicates camera should not return to default.
  100520. */
  100521. set: function (speed) {
  100522. this._elevationReturnTime = speed;
  100523. },
  100524. enumerable: true,
  100525. configurable: true
  100526. });
  100527. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  100528. /**
  100529. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100530. */
  100531. get: function () {
  100532. return this._elevationReturnWaitTime;
  100533. },
  100534. /**
  100535. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100536. */
  100537. set: function (time) {
  100538. this._elevationReturnWaitTime = time;
  100539. },
  100540. enumerable: true,
  100541. configurable: true
  100542. });
  100543. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  100544. /**
  100545. * Gets the flag that indicates if user zooming should stop animation.
  100546. */
  100547. get: function () {
  100548. return this._zoomStopsAnimation;
  100549. },
  100550. /**
  100551. * Sets the flag that indicates if user zooming should stop animation.
  100552. */
  100553. set: function (flag) {
  100554. this._zoomStopsAnimation = flag;
  100555. },
  100556. enumerable: true,
  100557. configurable: true
  100558. });
  100559. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  100560. /**
  100561. * Gets the transition time when framing the mesh, in milliseconds
  100562. */
  100563. get: function () {
  100564. return this._framingTime;
  100565. },
  100566. /**
  100567. * Sets the transition time when framing the mesh, in milliseconds
  100568. */
  100569. set: function (time) {
  100570. this._framingTime = time;
  100571. },
  100572. enumerable: true,
  100573. configurable: true
  100574. });
  100575. FramingBehavior.prototype.init = function () {
  100576. // Do notihng
  100577. };
  100578. FramingBehavior.prototype.attach = function (camera) {
  100579. var _this = this;
  100580. this._attachedCamera = camera;
  100581. var scene = this._attachedCamera.getScene();
  100582. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  100583. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100584. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100585. _this._isPointerDown = true;
  100586. return;
  100587. }
  100588. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100589. _this._isPointerDown = false;
  100590. }
  100591. });
  100592. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100593. if (mesh) {
  100594. _this.zoomOnMesh(mesh);
  100595. }
  100596. });
  100597. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100598. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100599. _this._applyUserInteraction();
  100600. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  100601. // back to the default position after a given timeout
  100602. _this._maintainCameraAboveGround();
  100603. });
  100604. };
  100605. FramingBehavior.prototype.detach = function () {
  100606. if (!this._attachedCamera) {
  100607. return;
  100608. }
  100609. var scene = this._attachedCamera.getScene();
  100610. if (this._onPrePointerObservableObserver) {
  100611. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100612. }
  100613. if (this._onAfterCheckInputsObserver) {
  100614. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100615. }
  100616. if (this._onMeshTargetChangedObserver) {
  100617. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100618. }
  100619. this._attachedCamera = null;
  100620. };
  100621. /**
  100622. * Targets the given mesh and updates zoom level accordingly.
  100623. * @param mesh The mesh to target.
  100624. * @param radius Optional. If a cached radius position already exists, overrides default.
  100625. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100626. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100627. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100628. */
  100629. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100630. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100631. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100632. mesh.computeWorldMatrix(true);
  100633. var boundingBox = mesh.getBoundingInfo().boundingBox;
  100634. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  100635. };
  100636. /**
  100637. * Targets the given mesh with its children and updates zoom level accordingly.
  100638. * @param mesh The mesh to target.
  100639. * @param radius Optional. If a cached radius position already exists, overrides default.
  100640. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100641. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100642. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100643. */
  100644. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100645. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100646. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100647. mesh.computeWorldMatrix(true);
  100648. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  100649. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  100650. };
  100651. /**
  100652. * Targets the given meshes with their children and updates zoom level accordingly.
  100653. * @param meshes The mesh to target.
  100654. * @param radius Optional. If a cached radius position already exists, overrides default.
  100655. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100656. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100657. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100658. */
  100659. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  100660. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100661. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100662. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  100663. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  100664. for (var i = 0; i < meshes.length; i++) {
  100665. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  100666. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  100667. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  100668. }
  100669. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  100670. };
  100671. /**
  100672. * Targets the given mesh and updates zoom level accordingly.
  100673. * @param mesh The mesh to target.
  100674. * @param radius Optional. If a cached radius position already exists, overrides default.
  100675. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100676. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100677. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100678. */
  100679. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  100680. var _this = this;
  100681. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100682. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100683. var zoomTarget;
  100684. if (!this._attachedCamera) {
  100685. return;
  100686. }
  100687. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  100688. var bottom = minimumWorld.y;
  100689. var top = maximumWorld.y;
  100690. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  100691. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  100692. if (focusOnOriginXZ) {
  100693. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  100694. }
  100695. else {
  100696. var centerWorld = minimumWorld.add(radiusWorld);
  100697. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  100698. }
  100699. if (!this._vectorTransition) {
  100700. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  100701. }
  100702. this._betaIsAnimating = true;
  100703. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  100704. if (animatable) {
  100705. this._animatables.push(animatable);
  100706. }
  100707. // sets the radius and lower radius bounds
  100708. // Small delta ensures camera is not always at lower zoom limit.
  100709. var radius = 0;
  100710. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  100711. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100712. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  100713. radius = position;
  100714. }
  100715. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100716. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100717. if (this._attachedCamera.lowerRadiusLimit === null) {
  100718. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  100719. }
  100720. }
  100721. // Set sensibilities
  100722. var extend = maximumWorld.subtract(minimumWorld).length();
  100723. this._attachedCamera.panningSensibility = 5000 / extend;
  100724. this._attachedCamera.wheelPrecision = 100 / radius;
  100725. // transition to new radius
  100726. if (!this._radiusTransition) {
  100727. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100728. }
  100729. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  100730. _this.stopAllAnimations();
  100731. if (onAnimationEnd) {
  100732. onAnimationEnd();
  100733. }
  100734. if (_this._attachedCamera) {
  100735. _this._attachedCamera.storeState();
  100736. }
  100737. });
  100738. if (animatable) {
  100739. this._animatables.push(animatable);
  100740. }
  100741. };
  100742. /**
  100743. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  100744. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  100745. * frustum width.
  100746. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  100747. * to fully enclose the mesh in the viewing frustum.
  100748. */
  100749. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  100750. var size = maximumWorld.subtract(minimumWorld);
  100751. var boxVectorGlobalDiagonal = size.length();
  100752. var frustumSlope = this._getFrustumSlope();
  100753. // Formula for setting distance
  100754. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  100755. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  100756. // Horizon distance
  100757. var radius = radiusWithoutFraming * this._radiusScale;
  100758. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  100759. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  100760. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  100761. var camera = this._attachedCamera;
  100762. if (!camera) {
  100763. return 0;
  100764. }
  100765. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100766. // Don't exceed the requested limit
  100767. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  100768. }
  100769. // Don't exceed the upper radius limit
  100770. if (camera.upperRadiusLimit) {
  100771. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  100772. }
  100773. return distance;
  100774. };
  100775. /**
  100776. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  100777. * is automatically returned to its default position (expected to be above ground plane).
  100778. */
  100779. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  100780. var _this = this;
  100781. if (this._elevationReturnTime < 0) {
  100782. return;
  100783. }
  100784. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  100785. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  100786. var limitBeta = Math.PI * 0.5;
  100787. // Bring the camera back up if below the ground plane
  100788. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  100789. this._betaIsAnimating = true;
  100790. //Transition to new position
  100791. this.stopAllAnimations();
  100792. if (!this._betaTransition) {
  100793. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100794. }
  100795. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  100796. _this._clearAnimationLocks();
  100797. _this.stopAllAnimations();
  100798. });
  100799. if (animatabe) {
  100800. this._animatables.push(animatabe);
  100801. }
  100802. }
  100803. };
  100804. /**
  100805. * Returns the frustum slope based on the canvas ratio and camera FOV
  100806. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  100807. */
  100808. FramingBehavior.prototype._getFrustumSlope = function () {
  100809. // Calculate the viewport ratio
  100810. // Aspect Ratio is Height/Width.
  100811. var camera = this._attachedCamera;
  100812. if (!camera) {
  100813. return BABYLON.Vector2.Zero();
  100814. }
  100815. var engine = camera.getScene().getEngine();
  100816. var aspectRatio = engine.getAspectRatio(camera);
  100817. // Camera FOV is the vertical field of view (top-bottom) in radians.
  100818. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  100819. var frustumSlopeY = Math.tan(camera.fov / 2);
  100820. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  100821. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  100822. // along the forward vector.
  100823. var frustumSlopeX = frustumSlopeY * aspectRatio;
  100824. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  100825. };
  100826. /**
  100827. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  100828. */
  100829. FramingBehavior.prototype._clearAnimationLocks = function () {
  100830. this._betaIsAnimating = false;
  100831. };
  100832. /**
  100833. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100834. */
  100835. FramingBehavior.prototype._applyUserInteraction = function () {
  100836. if (this.isUserIsMoving) {
  100837. this._lastInteractionTime = BABYLON.Tools.Now;
  100838. this.stopAllAnimations();
  100839. this._clearAnimationLocks();
  100840. }
  100841. };
  100842. /**
  100843. * Stops and removes all animations that have been applied to the camera
  100844. */
  100845. FramingBehavior.prototype.stopAllAnimations = function () {
  100846. if (this._attachedCamera) {
  100847. this._attachedCamera.animations = [];
  100848. }
  100849. while (this._animatables.length) {
  100850. if (this._animatables[0]) {
  100851. this._animatables[0].onAnimationEnd = null;
  100852. this._animatables[0].stop();
  100853. }
  100854. this._animatables.shift();
  100855. }
  100856. };
  100857. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  100858. /**
  100859. * Gets a value indicating if the user is moving the camera
  100860. */
  100861. get: function () {
  100862. if (!this._attachedCamera) {
  100863. return false;
  100864. }
  100865. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100866. this._attachedCamera.inertialBetaOffset !== 0 ||
  100867. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100868. this._attachedCamera.inertialPanningX !== 0 ||
  100869. this._attachedCamera.inertialPanningY !== 0 ||
  100870. this._isPointerDown;
  100871. },
  100872. enumerable: true,
  100873. configurable: true
  100874. });
  100875. /**
  100876. * The easing function used by animations
  100877. */
  100878. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  100879. /**
  100880. * The easing mode used by animations
  100881. */
  100882. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  100883. // Statics
  100884. /**
  100885. * The camera can move all the way towards the mesh.
  100886. */
  100887. FramingBehavior.IgnoreBoundsSizeMode = 0;
  100888. /**
  100889. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  100890. */
  100891. FramingBehavior.FitFrustumSidesMode = 1;
  100892. return FramingBehavior;
  100893. }());
  100894. BABYLON.FramingBehavior = FramingBehavior;
  100895. })(BABYLON || (BABYLON = {}));
  100896. //# sourceMappingURL=babylon.framingBehavior.js.map
  100897. var BABYLON;
  100898. (function (BABYLON) {
  100899. /**
  100900. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  100901. */
  100902. var BouncingBehavior = /** @class */ (function () {
  100903. function BouncingBehavior() {
  100904. /**
  100905. * The duration of the animation, in milliseconds
  100906. */
  100907. this.transitionDuration = 450;
  100908. /**
  100909. * Length of the distance animated by the transition when lower radius is reached
  100910. */
  100911. this.lowerRadiusTransitionRange = 2;
  100912. /**
  100913. * Length of the distance animated by the transition when upper radius is reached
  100914. */
  100915. this.upperRadiusTransitionRange = -2;
  100916. this._autoTransitionRange = false;
  100917. // Animations
  100918. this._radiusIsAnimating = false;
  100919. this._radiusBounceTransition = null;
  100920. this._animatables = new Array();
  100921. }
  100922. Object.defineProperty(BouncingBehavior.prototype, "name", {
  100923. get: function () {
  100924. return "Bouncing";
  100925. },
  100926. enumerable: true,
  100927. configurable: true
  100928. });
  100929. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  100930. /**
  100931. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100932. */
  100933. get: function () {
  100934. return this._autoTransitionRange;
  100935. },
  100936. /**
  100937. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100938. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  100939. */
  100940. set: function (value) {
  100941. var _this = this;
  100942. if (this._autoTransitionRange === value) {
  100943. return;
  100944. }
  100945. this._autoTransitionRange = value;
  100946. var camera = this._attachedCamera;
  100947. if (!camera) {
  100948. return;
  100949. }
  100950. if (value) {
  100951. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100952. if (!mesh) {
  100953. return;
  100954. }
  100955. mesh.computeWorldMatrix(true);
  100956. var diagonal = mesh.getBoundingInfo().diagonalLength;
  100957. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  100958. _this.upperRadiusTransitionRange = diagonal * 0.05;
  100959. });
  100960. }
  100961. else if (this._onMeshTargetChangedObserver) {
  100962. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100963. }
  100964. },
  100965. enumerable: true,
  100966. configurable: true
  100967. });
  100968. BouncingBehavior.prototype.init = function () {
  100969. // Do notihng
  100970. };
  100971. BouncingBehavior.prototype.attach = function (camera) {
  100972. var _this = this;
  100973. this._attachedCamera = camera;
  100974. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100975. if (!_this._attachedCamera) {
  100976. return;
  100977. }
  100978. // Add the bounce animation to the lower radius limit
  100979. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  100980. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  100981. }
  100982. // Add the bounce animation to the upper radius limit
  100983. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  100984. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  100985. }
  100986. });
  100987. };
  100988. BouncingBehavior.prototype.detach = function () {
  100989. if (!this._attachedCamera) {
  100990. return;
  100991. }
  100992. if (this._onAfterCheckInputsObserver) {
  100993. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100994. }
  100995. if (this._onMeshTargetChangedObserver) {
  100996. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100997. }
  100998. this._attachedCamera = null;
  100999. };
  101000. /**
  101001. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  101002. * @param radiusLimit The limit to check against.
  101003. * @return Bool to indicate if at limit.
  101004. */
  101005. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  101006. if (!this._attachedCamera) {
  101007. return false;
  101008. }
  101009. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  101010. return true;
  101011. }
  101012. return false;
  101013. };
  101014. /**
  101015. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  101016. * @param radiusDelta The delta by which to animate to. Can be negative.
  101017. */
  101018. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  101019. var _this = this;
  101020. if (!this._attachedCamera) {
  101021. return;
  101022. }
  101023. if (!this._radiusBounceTransition) {
  101024. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  101025. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  101026. }
  101027. // Prevent zoom until bounce has completed
  101028. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  101029. this._attachedCamera.wheelPrecision = Infinity;
  101030. this._attachedCamera.inertialRadiusOffset = 0;
  101031. // Animate to the radius limit
  101032. this.stopAllAnimations();
  101033. this._radiusIsAnimating = true;
  101034. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  101035. if (animatable) {
  101036. this._animatables.push(animatable);
  101037. }
  101038. };
  101039. /**
  101040. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  101041. */
  101042. BouncingBehavior.prototype._clearAnimationLocks = function () {
  101043. this._radiusIsAnimating = false;
  101044. if (this._attachedCamera) {
  101045. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  101046. }
  101047. };
  101048. /**
  101049. * Stops and removes all animations that have been applied to the camera
  101050. */
  101051. BouncingBehavior.prototype.stopAllAnimations = function () {
  101052. if (this._attachedCamera) {
  101053. this._attachedCamera.animations = [];
  101054. }
  101055. while (this._animatables.length) {
  101056. this._animatables[0].onAnimationEnd = null;
  101057. this._animatables[0].stop();
  101058. this._animatables.shift();
  101059. }
  101060. };
  101061. /**
  101062. * The easing function used by animations
  101063. */
  101064. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  101065. /**
  101066. * The easing mode used by animations
  101067. */
  101068. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  101069. return BouncingBehavior;
  101070. }());
  101071. BABYLON.BouncingBehavior = BouncingBehavior;
  101072. })(BABYLON || (BABYLON = {}));
  101073. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  101074. var BABYLON;
  101075. (function (BABYLON) {
  101076. var AutoRotationBehavior = /** @class */ (function () {
  101077. function AutoRotationBehavior() {
  101078. this._zoomStopsAnimation = false;
  101079. this._idleRotationSpeed = 0.05;
  101080. this._idleRotationWaitTime = 2000;
  101081. this._idleRotationSpinupTime = 2000;
  101082. this._isPointerDown = false;
  101083. this._lastFrameTime = null;
  101084. this._lastInteractionTime = -Infinity;
  101085. this._cameraRotationSpeed = 0;
  101086. this._lastFrameRadius = 0;
  101087. }
  101088. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  101089. get: function () {
  101090. return "AutoRotation";
  101091. },
  101092. enumerable: true,
  101093. configurable: true
  101094. });
  101095. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  101096. /**
  101097. * Gets the flag that indicates if user zooming should stop animation.
  101098. */
  101099. get: function () {
  101100. return this._zoomStopsAnimation;
  101101. },
  101102. /**
  101103. * Sets the flag that indicates if user zooming should stop animation.
  101104. */
  101105. set: function (flag) {
  101106. this._zoomStopsAnimation = flag;
  101107. },
  101108. enumerable: true,
  101109. configurable: true
  101110. });
  101111. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  101112. /**
  101113. * Gets the default speed at which the camera rotates around the model.
  101114. */
  101115. get: function () {
  101116. return this._idleRotationSpeed;
  101117. },
  101118. /**
  101119. * Sets the default speed at which the camera rotates around the model.
  101120. */
  101121. set: function (speed) {
  101122. this._idleRotationSpeed = speed;
  101123. },
  101124. enumerable: true,
  101125. configurable: true
  101126. });
  101127. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  101128. /**
  101129. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  101130. */
  101131. get: function () {
  101132. return this._idleRotationWaitTime;
  101133. },
  101134. /**
  101135. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  101136. */
  101137. set: function (time) {
  101138. this._idleRotationWaitTime = time;
  101139. },
  101140. enumerable: true,
  101141. configurable: true
  101142. });
  101143. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  101144. /**
  101145. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101146. */
  101147. get: function () {
  101148. return this._idleRotationSpinupTime;
  101149. },
  101150. /**
  101151. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101152. */
  101153. set: function (time) {
  101154. this._idleRotationSpinupTime = time;
  101155. },
  101156. enumerable: true,
  101157. configurable: true
  101158. });
  101159. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  101160. /**
  101161. * Gets a value indicating if the camera is currently rotating because of this behavior
  101162. */
  101163. get: function () {
  101164. return Math.abs(this._cameraRotationSpeed) > 0;
  101165. },
  101166. enumerable: true,
  101167. configurable: true
  101168. });
  101169. AutoRotationBehavior.prototype.init = function () {
  101170. // Do notihng
  101171. };
  101172. AutoRotationBehavior.prototype.attach = function (camera) {
  101173. var _this = this;
  101174. this._attachedCamera = camera;
  101175. var scene = this._attachedCamera.getScene();
  101176. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101177. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101178. _this._isPointerDown = true;
  101179. return;
  101180. }
  101181. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101182. _this._isPointerDown = false;
  101183. }
  101184. });
  101185. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101186. var now = BABYLON.Tools.Now;
  101187. var dt = 0;
  101188. if (_this._lastFrameTime != null) {
  101189. dt = now - _this._lastFrameTime;
  101190. }
  101191. _this._lastFrameTime = now;
  101192. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101193. _this._applyUserInteraction();
  101194. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  101195. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  101196. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  101197. // Step camera rotation by rotation speed
  101198. if (_this._attachedCamera) {
  101199. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  101200. }
  101201. });
  101202. };
  101203. AutoRotationBehavior.prototype.detach = function () {
  101204. if (!this._attachedCamera) {
  101205. return;
  101206. }
  101207. var scene = this._attachedCamera.getScene();
  101208. if (this._onPrePointerObservableObserver) {
  101209. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101210. }
  101211. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101212. this._attachedCamera = null;
  101213. };
  101214. /**
  101215. * Returns true if user is scrolling.
  101216. * @return true if user is scrolling.
  101217. */
  101218. AutoRotationBehavior.prototype._userIsZooming = function () {
  101219. if (!this._attachedCamera) {
  101220. return false;
  101221. }
  101222. return this._attachedCamera.inertialRadiusOffset !== 0;
  101223. };
  101224. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  101225. if (!this._attachedCamera) {
  101226. return false;
  101227. }
  101228. var zoomHasHitLimit = false;
  101229. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  101230. zoomHasHitLimit = true;
  101231. }
  101232. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  101233. this._lastFrameRadius = this._attachedCamera.radius;
  101234. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  101235. };
  101236. /**
  101237. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101238. */
  101239. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  101240. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  101241. this._lastInteractionTime = BABYLON.Tools.Now;
  101242. }
  101243. };
  101244. // Tools
  101245. AutoRotationBehavior.prototype._userIsMoving = function () {
  101246. if (!this._attachedCamera) {
  101247. return false;
  101248. }
  101249. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101250. this._attachedCamera.inertialBetaOffset !== 0 ||
  101251. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101252. this._attachedCamera.inertialPanningX !== 0 ||
  101253. this._attachedCamera.inertialPanningY !== 0 ||
  101254. this._isPointerDown;
  101255. };
  101256. return AutoRotationBehavior;
  101257. }());
  101258. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  101259. })(BABYLON || (BABYLON = {}));
  101260. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  101261. var BABYLON;
  101262. (function (BABYLON) {
  101263. var NullEngineOptions = /** @class */ (function () {
  101264. function NullEngineOptions() {
  101265. this.renderWidth = 512;
  101266. this.renderHeight = 256;
  101267. this.textureSize = 512;
  101268. this.deterministicLockstep = false;
  101269. this.lockstepMaxSteps = 4;
  101270. }
  101271. return NullEngineOptions;
  101272. }());
  101273. BABYLON.NullEngineOptions = NullEngineOptions;
  101274. /**
  101275. * The null engine class provides support for headless version of babylon.js.
  101276. * This can be used in server side scenario or for testing purposes
  101277. */
  101278. var NullEngine = /** @class */ (function (_super) {
  101279. __extends(NullEngine, _super);
  101280. function NullEngine(options) {
  101281. if (options === void 0) { options = new NullEngineOptions(); }
  101282. var _this = _super.call(this, null) || this;
  101283. if (options.deterministicLockstep === undefined) {
  101284. options.deterministicLockstep = false;
  101285. }
  101286. if (options.lockstepMaxSteps === undefined) {
  101287. options.lockstepMaxSteps = 4;
  101288. }
  101289. _this._options = options;
  101290. // Init caps
  101291. // We consider we are on a webgl1 capable device
  101292. _this._caps = new BABYLON.EngineCapabilities();
  101293. _this._caps.maxTexturesImageUnits = 16;
  101294. _this._caps.maxVertexTextureImageUnits = 16;
  101295. _this._caps.maxTextureSize = 512;
  101296. _this._caps.maxCubemapTextureSize = 512;
  101297. _this._caps.maxRenderTextureSize = 512;
  101298. _this._caps.maxVertexAttribs = 16;
  101299. _this._caps.maxVaryingVectors = 16;
  101300. _this._caps.maxFragmentUniformVectors = 16;
  101301. _this._caps.maxVertexUniformVectors = 16;
  101302. // Extensions
  101303. _this._caps.standardDerivatives = false;
  101304. _this._caps.astc = null;
  101305. _this._caps.s3tc = null;
  101306. _this._caps.pvrtc = null;
  101307. _this._caps.etc1 = null;
  101308. _this._caps.etc2 = null;
  101309. _this._caps.textureAnisotropicFilterExtension = null;
  101310. _this._caps.maxAnisotropy = 0;
  101311. _this._caps.uintIndices = false;
  101312. _this._caps.fragmentDepthSupported = false;
  101313. _this._caps.highPrecisionShaderSupported = true;
  101314. _this._caps.colorBufferFloat = false;
  101315. _this._caps.textureFloat = false;
  101316. _this._caps.textureFloatLinearFiltering = false;
  101317. _this._caps.textureFloatRender = false;
  101318. _this._caps.textureHalfFloat = false;
  101319. _this._caps.textureHalfFloatLinearFiltering = false;
  101320. _this._caps.textureHalfFloatRender = false;
  101321. _this._caps.textureLOD = false;
  101322. _this._caps.drawBuffersExtension = false;
  101323. _this._caps.depthTextureExtension = false;
  101324. _this._caps.vertexArrayObject = false;
  101325. _this._caps.instancedArrays = false;
  101326. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  101327. // Wrappers
  101328. if (typeof URL === "undefined") {
  101329. URL = {
  101330. createObjectURL: function () { },
  101331. revokeObjectURL: function () { }
  101332. };
  101333. }
  101334. if (typeof Blob === "undefined") {
  101335. Blob = function () { };
  101336. }
  101337. return _this;
  101338. }
  101339. NullEngine.prototype.isDeterministicLockStep = function () {
  101340. return this._options.deterministicLockstep;
  101341. };
  101342. NullEngine.prototype.getLockstepMaxSteps = function () {
  101343. return this._options.lockstepMaxSteps;
  101344. };
  101345. NullEngine.prototype.getHardwareScalingLevel = function () {
  101346. return 1.0;
  101347. };
  101348. NullEngine.prototype.createVertexBuffer = function (vertices) {
  101349. return {
  101350. capacity: 0,
  101351. references: 1,
  101352. is32Bits: false
  101353. };
  101354. };
  101355. NullEngine.prototype.createIndexBuffer = function (indices) {
  101356. return {
  101357. capacity: 0,
  101358. references: 1,
  101359. is32Bits: false
  101360. };
  101361. };
  101362. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  101363. if (stencil === void 0) { stencil = false; }
  101364. };
  101365. NullEngine.prototype.getRenderWidth = function (useScreen) {
  101366. if (useScreen === void 0) { useScreen = false; }
  101367. if (!useScreen && this._currentRenderTarget) {
  101368. return this._currentRenderTarget.width;
  101369. }
  101370. return this._options.renderWidth;
  101371. };
  101372. NullEngine.prototype.getRenderHeight = function (useScreen) {
  101373. if (useScreen === void 0) { useScreen = false; }
  101374. if (!useScreen && this._currentRenderTarget) {
  101375. return this._currentRenderTarget.height;
  101376. }
  101377. return this._options.renderHeight;
  101378. };
  101379. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  101380. this._cachedViewport = viewport;
  101381. };
  101382. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  101383. return {
  101384. transformFeedback: null,
  101385. __SPECTOR_rebuildProgram: null
  101386. };
  101387. };
  101388. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  101389. return [];
  101390. };
  101391. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  101392. return [];
  101393. };
  101394. NullEngine.prototype.bindSamplers = function (effect) {
  101395. this._currentEffect = null;
  101396. };
  101397. NullEngine.prototype.enableEffect = function (effect) {
  101398. this._currentEffect = effect;
  101399. if (effect.onBind) {
  101400. effect.onBind(effect);
  101401. }
  101402. effect.onBindObservable.notifyObservers(effect);
  101403. };
  101404. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  101405. if (zOffset === void 0) { zOffset = 0; }
  101406. if (reverseSide === void 0) { reverseSide = false; }
  101407. };
  101408. NullEngine.prototype.setIntArray = function (uniform, array) {
  101409. };
  101410. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  101411. };
  101412. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  101413. };
  101414. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  101415. };
  101416. NullEngine.prototype.setFloatArray = function (uniform, array) {
  101417. };
  101418. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  101419. };
  101420. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  101421. };
  101422. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  101423. };
  101424. NullEngine.prototype.setArray = function (uniform, array) {
  101425. };
  101426. NullEngine.prototype.setArray2 = function (uniform, array) {
  101427. };
  101428. NullEngine.prototype.setArray3 = function (uniform, array) {
  101429. };
  101430. NullEngine.prototype.setArray4 = function (uniform, array) {
  101431. };
  101432. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  101433. };
  101434. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  101435. };
  101436. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  101437. };
  101438. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  101439. };
  101440. NullEngine.prototype.setFloat = function (uniform, value) {
  101441. };
  101442. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  101443. };
  101444. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  101445. };
  101446. NullEngine.prototype.setBool = function (uniform, bool) {
  101447. };
  101448. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  101449. };
  101450. NullEngine.prototype.setColor3 = function (uniform, color3) {
  101451. };
  101452. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  101453. };
  101454. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  101455. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  101456. if (this._alphaMode === mode) {
  101457. return;
  101458. }
  101459. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  101460. if (!noDepthWriteChange) {
  101461. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  101462. }
  101463. this._alphaMode = mode;
  101464. };
  101465. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  101466. };
  101467. NullEngine.prototype.wipeCaches = function (bruteForce) {
  101468. if (this.preventCacheWipeBetweenFrames) {
  101469. return;
  101470. }
  101471. this.resetTextureCache();
  101472. this._currentEffect = null;
  101473. if (bruteForce) {
  101474. this._currentProgram = null;
  101475. this._stencilState.reset();
  101476. this._depthCullingState.reset();
  101477. this._alphaState.reset();
  101478. }
  101479. this._cachedVertexBuffers = null;
  101480. this._cachedIndexBuffer = null;
  101481. this._cachedEffectForVertexBuffers = null;
  101482. };
  101483. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  101484. };
  101485. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  101486. };
  101487. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  101488. };
  101489. NullEngine.prototype._createTexture = function () {
  101490. return {};
  101491. };
  101492. NullEngine.prototype._releaseTexture = function (texture) {
  101493. };
  101494. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  101495. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101496. if (onLoad === void 0) { onLoad = null; }
  101497. if (onError === void 0) { onError = null; }
  101498. if (buffer === void 0) { buffer = null; }
  101499. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  101500. var url = String(urlArg);
  101501. texture.url = url;
  101502. texture.generateMipMaps = !noMipmap;
  101503. texture.samplingMode = samplingMode;
  101504. texture.invertY = invertY;
  101505. texture.baseWidth = this._options.textureSize;
  101506. texture.baseHeight = this._options.textureSize;
  101507. texture.width = this._options.textureSize;
  101508. texture.height = this._options.textureSize;
  101509. if (format) {
  101510. texture.format = format;
  101511. }
  101512. texture.isReady = true;
  101513. if (onLoad) {
  101514. onLoad();
  101515. }
  101516. this._internalTexturesCache.push(texture);
  101517. return texture;
  101518. };
  101519. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  101520. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  101521. if (options !== undefined && typeof options === "object") {
  101522. fullOptions.generateMipMaps = options.generateMipMaps;
  101523. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  101524. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  101525. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  101526. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  101527. }
  101528. else {
  101529. fullOptions.generateMipMaps = options;
  101530. fullOptions.generateDepthBuffer = true;
  101531. fullOptions.generateStencilBuffer = false;
  101532. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101533. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  101534. }
  101535. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  101536. var width = size.width || size;
  101537. var height = size.height || size;
  101538. texture._depthStencilBuffer = {};
  101539. texture._framebuffer = {};
  101540. texture.baseWidth = width;
  101541. texture.baseHeight = height;
  101542. texture.width = width;
  101543. texture.height = height;
  101544. texture.isReady = true;
  101545. texture.samples = 1;
  101546. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  101547. texture.samplingMode = fullOptions.samplingMode;
  101548. texture.type = fullOptions.type;
  101549. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  101550. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  101551. this._internalTexturesCache.push(texture);
  101552. return texture;
  101553. };
  101554. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  101555. texture.samplingMode = samplingMode;
  101556. };
  101557. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  101558. if (this._currentRenderTarget) {
  101559. this.unBindFramebuffer(this._currentRenderTarget);
  101560. }
  101561. this._currentRenderTarget = texture;
  101562. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  101563. if (this._cachedViewport && !forceFullscreenViewport) {
  101564. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  101565. }
  101566. };
  101567. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  101568. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  101569. this._currentRenderTarget = null;
  101570. if (onBeforeUnbind) {
  101571. if (texture._MSAAFramebuffer) {
  101572. this._currentFramebuffer = texture._framebuffer;
  101573. }
  101574. onBeforeUnbind();
  101575. }
  101576. this._currentFramebuffer = null;
  101577. };
  101578. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  101579. var vbo = {
  101580. capacity: 1,
  101581. references: 1,
  101582. is32Bits: false
  101583. };
  101584. return vbo;
  101585. };
  101586. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  101587. if (premulAlpha === void 0) { premulAlpha = false; }
  101588. };
  101589. /**
  101590. * Get the current error code of the webGL context
  101591. * @returns the error code
  101592. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  101593. */
  101594. NullEngine.prototype.getError = function () {
  101595. return 0;
  101596. };
  101597. /** @hidden */
  101598. NullEngine.prototype._getUnpackAlignement = function () {
  101599. return 1;
  101600. };
  101601. /** @hidden */
  101602. NullEngine.prototype._unpackFlipY = function (value) {
  101603. };
  101604. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  101605. if (offset === void 0) { offset = 0; }
  101606. };
  101607. /**
  101608. * Updates a dynamic vertex buffer.
  101609. * @param vertexBuffer the vertex buffer to update
  101610. * @param data the data used to update the vertex buffer
  101611. * @param byteOffset the byte offset of the data (optional)
  101612. * @param byteLength the byte length of the data (optional)
  101613. */
  101614. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  101615. };
  101616. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  101617. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  101618. this._boundTexturesCache[this._activeChannel] = texture;
  101619. return true;
  101620. }
  101621. return false;
  101622. };
  101623. NullEngine.prototype._bindTexture = function (channel, texture) {
  101624. if (channel < 0) {
  101625. return;
  101626. }
  101627. this._bindTextureDirectly(0, texture);
  101628. };
  101629. NullEngine.prototype._releaseBuffer = function (buffer) {
  101630. buffer.references--;
  101631. if (buffer.references === 0) {
  101632. return true;
  101633. }
  101634. return false;
  101635. };
  101636. NullEngine.prototype.releaseEffects = function () {
  101637. };
  101638. NullEngine.prototype.displayLoadingUI = function () {
  101639. };
  101640. NullEngine.prototype.hideLoadingUI = function () {
  101641. };
  101642. /** @hidden */
  101643. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  101644. if (faceIndex === void 0) { faceIndex = 0; }
  101645. if (lod === void 0) { lod = 0; }
  101646. };
  101647. /** @hidden */
  101648. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  101649. if (faceIndex === void 0) { faceIndex = 0; }
  101650. if (lod === void 0) { lod = 0; }
  101651. };
  101652. /** @hidden */
  101653. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  101654. if (faceIndex === void 0) { faceIndex = 0; }
  101655. if (lod === void 0) { lod = 0; }
  101656. };
  101657. /** @hidden */
  101658. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  101659. if (faceIndex === void 0) { faceIndex = 0; }
  101660. if (lod === void 0) { lod = 0; }
  101661. };
  101662. return NullEngine;
  101663. }(BABYLON.Engine));
  101664. BABYLON.NullEngine = NullEngine;
  101665. })(BABYLON || (BABYLON = {}));
  101666. //# sourceMappingURL=babylon.nullEngine.js.map
  101667. var BABYLON;
  101668. (function (BABYLON) {
  101669. /**
  101670. * This class can be used to get instrumentation data from a Babylon engine
  101671. */
  101672. var EngineInstrumentation = /** @class */ (function () {
  101673. function EngineInstrumentation(engine) {
  101674. this.engine = engine;
  101675. this._captureGPUFrameTime = false;
  101676. this._gpuFrameTime = new BABYLON.PerfCounter();
  101677. this._captureShaderCompilationTime = false;
  101678. this._shaderCompilationTime = new BABYLON.PerfCounter();
  101679. // Observers
  101680. this._onBeginFrameObserver = null;
  101681. this._onEndFrameObserver = null;
  101682. this._onBeforeShaderCompilationObserver = null;
  101683. this._onAfterShaderCompilationObserver = null;
  101684. }
  101685. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  101686. // Properties
  101687. /**
  101688. * Gets the perf counter used for GPU frame time
  101689. */
  101690. get: function () {
  101691. return this._gpuFrameTime;
  101692. },
  101693. enumerable: true,
  101694. configurable: true
  101695. });
  101696. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  101697. /**
  101698. * Gets the GPU frame time capture status
  101699. */
  101700. get: function () {
  101701. return this._captureGPUFrameTime;
  101702. },
  101703. /**
  101704. * Enable or disable the GPU frame time capture
  101705. */
  101706. set: function (value) {
  101707. var _this = this;
  101708. if (value === this._captureGPUFrameTime) {
  101709. return;
  101710. }
  101711. this._captureGPUFrameTime = value;
  101712. if (value) {
  101713. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  101714. if (!_this._gpuFrameTimeToken) {
  101715. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  101716. }
  101717. });
  101718. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  101719. if (!_this._gpuFrameTimeToken) {
  101720. return;
  101721. }
  101722. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  101723. if (time > -1) {
  101724. _this._gpuFrameTimeToken = null;
  101725. _this._gpuFrameTime.fetchNewFrame();
  101726. _this._gpuFrameTime.addCount(time, true);
  101727. }
  101728. });
  101729. }
  101730. else {
  101731. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101732. this._onBeginFrameObserver = null;
  101733. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101734. this._onEndFrameObserver = null;
  101735. }
  101736. },
  101737. enumerable: true,
  101738. configurable: true
  101739. });
  101740. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  101741. /**
  101742. * Gets the perf counter used for shader compilation time
  101743. */
  101744. get: function () {
  101745. return this._shaderCompilationTime;
  101746. },
  101747. enumerable: true,
  101748. configurable: true
  101749. });
  101750. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  101751. /**
  101752. * Gets the shader compilation time capture status
  101753. */
  101754. get: function () {
  101755. return this._captureShaderCompilationTime;
  101756. },
  101757. /**
  101758. * Enable or disable the shader compilation time capture
  101759. */
  101760. set: function (value) {
  101761. var _this = this;
  101762. if (value === this._captureShaderCompilationTime) {
  101763. return;
  101764. }
  101765. this._captureShaderCompilationTime = value;
  101766. if (value) {
  101767. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  101768. _this._shaderCompilationTime.fetchNewFrame();
  101769. _this._shaderCompilationTime.beginMonitoring();
  101770. });
  101771. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  101772. _this._shaderCompilationTime.endMonitoring();
  101773. });
  101774. }
  101775. else {
  101776. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101777. this._onBeforeShaderCompilationObserver = null;
  101778. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101779. this._onAfterShaderCompilationObserver = null;
  101780. }
  101781. },
  101782. enumerable: true,
  101783. configurable: true
  101784. });
  101785. EngineInstrumentation.prototype.dispose = function () {
  101786. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101787. this._onBeginFrameObserver = null;
  101788. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101789. this._onEndFrameObserver = null;
  101790. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101791. this._onBeforeShaderCompilationObserver = null;
  101792. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101793. this._onAfterShaderCompilationObserver = null;
  101794. this.engine = null;
  101795. };
  101796. return EngineInstrumentation;
  101797. }());
  101798. BABYLON.EngineInstrumentation = EngineInstrumentation;
  101799. })(BABYLON || (BABYLON = {}));
  101800. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  101801. var BABYLON;
  101802. (function (BABYLON) {
  101803. /**
  101804. * This class can be used to get instrumentation data from a Babylon engine
  101805. */
  101806. var SceneInstrumentation = /** @class */ (function () {
  101807. function SceneInstrumentation(scene) {
  101808. var _this = this;
  101809. this.scene = scene;
  101810. this._captureActiveMeshesEvaluationTime = false;
  101811. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  101812. this._captureRenderTargetsRenderTime = false;
  101813. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  101814. this._captureFrameTime = false;
  101815. this._frameTime = new BABYLON.PerfCounter();
  101816. this._captureRenderTime = false;
  101817. this._renderTime = new BABYLON.PerfCounter();
  101818. this._captureInterFrameTime = false;
  101819. this._interFrameTime = new BABYLON.PerfCounter();
  101820. this._captureParticlesRenderTime = false;
  101821. this._particlesRenderTime = new BABYLON.PerfCounter();
  101822. this._captureSpritesRenderTime = false;
  101823. this._spritesRenderTime = new BABYLON.PerfCounter();
  101824. this._capturePhysicsTime = false;
  101825. this._physicsTime = new BABYLON.PerfCounter();
  101826. this._captureAnimationsTime = false;
  101827. this._animationsTime = new BABYLON.PerfCounter();
  101828. this._captureCameraRenderTime = false;
  101829. this._cameraRenderTime = new BABYLON.PerfCounter();
  101830. // Observers
  101831. this._onBeforeActiveMeshesEvaluationObserver = null;
  101832. this._onAfterActiveMeshesEvaluationObserver = null;
  101833. this._onBeforeRenderTargetsRenderObserver = null;
  101834. this._onAfterRenderTargetsRenderObserver = null;
  101835. this._onAfterRenderObserver = null;
  101836. this._onBeforeDrawPhaseObserver = null;
  101837. this._onAfterDrawPhaseObserver = null;
  101838. this._onBeforeAnimationsObserver = null;
  101839. this._onBeforeParticlesRenderingObserver = null;
  101840. this._onAfterParticlesRenderingObserver = null;
  101841. this._onBeforeSpritesRenderingObserver = null;
  101842. this._onAfterSpritesRenderingObserver = null;
  101843. this._onBeforePhysicsObserver = null;
  101844. this._onAfterPhysicsObserver = null;
  101845. this._onAfterAnimationsObserver = null;
  101846. this._onBeforeCameraRenderObserver = null;
  101847. this._onAfterCameraRenderObserver = null;
  101848. // Before render
  101849. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  101850. if (_this._captureActiveMeshesEvaluationTime) {
  101851. _this._activeMeshesEvaluationTime.fetchNewFrame();
  101852. }
  101853. if (_this._captureRenderTargetsRenderTime) {
  101854. _this._renderTargetsRenderTime.fetchNewFrame();
  101855. }
  101856. if (_this._captureFrameTime) {
  101857. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  101858. _this._frameTime.beginMonitoring();
  101859. }
  101860. if (_this._captureInterFrameTime) {
  101861. _this._interFrameTime.endMonitoring();
  101862. }
  101863. if (_this._captureParticlesRenderTime) {
  101864. _this._particlesRenderTime.fetchNewFrame();
  101865. }
  101866. if (_this._captureSpritesRenderTime) {
  101867. _this._spritesRenderTime.fetchNewFrame();
  101868. }
  101869. if (_this._captureAnimationsTime) {
  101870. _this._animationsTime.beginMonitoring();
  101871. }
  101872. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  101873. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  101874. });
  101875. // After render
  101876. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  101877. if (_this._captureFrameTime) {
  101878. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  101879. _this._frameTime.endMonitoring();
  101880. }
  101881. if (_this._captureRenderTime) {
  101882. _this._renderTime.endMonitoring(false);
  101883. }
  101884. if (_this._captureInterFrameTime) {
  101885. _this._interFrameTime.beginMonitoring();
  101886. }
  101887. });
  101888. }
  101889. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  101890. // Properties
  101891. /**
  101892. * Gets the perf counter used for active meshes evaluation time
  101893. */
  101894. get: function () {
  101895. return this._activeMeshesEvaluationTime;
  101896. },
  101897. enumerable: true,
  101898. configurable: true
  101899. });
  101900. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  101901. /**
  101902. * Gets the active meshes evaluation time capture status
  101903. */
  101904. get: function () {
  101905. return this._captureActiveMeshesEvaluationTime;
  101906. },
  101907. /**
  101908. * Enable or disable the active meshes evaluation time capture
  101909. */
  101910. set: function (value) {
  101911. var _this = this;
  101912. if (value === this._captureActiveMeshesEvaluationTime) {
  101913. return;
  101914. }
  101915. this._captureActiveMeshesEvaluationTime = value;
  101916. if (value) {
  101917. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  101918. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  101919. _this._activeMeshesEvaluationTime.beginMonitoring();
  101920. });
  101921. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  101922. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  101923. _this._activeMeshesEvaluationTime.endMonitoring();
  101924. });
  101925. }
  101926. else {
  101927. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101928. this._onBeforeActiveMeshesEvaluationObserver = null;
  101929. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101930. this._onAfterActiveMeshesEvaluationObserver = null;
  101931. }
  101932. },
  101933. enumerable: true,
  101934. configurable: true
  101935. });
  101936. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  101937. /**
  101938. * Gets the perf counter used for render targets render time
  101939. */
  101940. get: function () {
  101941. return this._renderTargetsRenderTime;
  101942. },
  101943. enumerable: true,
  101944. configurable: true
  101945. });
  101946. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  101947. /**
  101948. * Gets the render targets render time capture status
  101949. */
  101950. get: function () {
  101951. return this._captureRenderTargetsRenderTime;
  101952. },
  101953. /**
  101954. * Enable or disable the render targets render time capture
  101955. */
  101956. set: function (value) {
  101957. var _this = this;
  101958. if (value === this._captureRenderTargetsRenderTime) {
  101959. return;
  101960. }
  101961. this._captureRenderTargetsRenderTime = value;
  101962. if (value) {
  101963. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  101964. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  101965. _this._renderTargetsRenderTime.beginMonitoring();
  101966. });
  101967. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  101968. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  101969. _this._renderTargetsRenderTime.endMonitoring(false);
  101970. });
  101971. }
  101972. else {
  101973. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101974. this._onBeforeRenderTargetsRenderObserver = null;
  101975. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101976. this._onAfterRenderTargetsRenderObserver = null;
  101977. }
  101978. },
  101979. enumerable: true,
  101980. configurable: true
  101981. });
  101982. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  101983. /**
  101984. * Gets the perf counter used for particles render time
  101985. */
  101986. get: function () {
  101987. return this._particlesRenderTime;
  101988. },
  101989. enumerable: true,
  101990. configurable: true
  101991. });
  101992. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  101993. /**
  101994. * Gets the particles render time capture status
  101995. */
  101996. get: function () {
  101997. return this._captureParticlesRenderTime;
  101998. },
  101999. /**
  102000. * Enable or disable the particles render time capture
  102001. */
  102002. set: function (value) {
  102003. var _this = this;
  102004. if (value === this._captureParticlesRenderTime) {
  102005. return;
  102006. }
  102007. this._captureParticlesRenderTime = value;
  102008. if (value) {
  102009. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  102010. BABYLON.Tools.StartPerformanceCounter("Particles");
  102011. _this._particlesRenderTime.beginMonitoring();
  102012. });
  102013. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  102014. BABYLON.Tools.EndPerformanceCounter("Particles");
  102015. _this._particlesRenderTime.endMonitoring(false);
  102016. });
  102017. }
  102018. else {
  102019. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102020. this._onBeforeParticlesRenderingObserver = null;
  102021. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102022. this._onAfterParticlesRenderingObserver = null;
  102023. }
  102024. },
  102025. enumerable: true,
  102026. configurable: true
  102027. });
  102028. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  102029. /**
  102030. * Gets the perf counter used for sprites render time
  102031. */
  102032. get: function () {
  102033. return this._spritesRenderTime;
  102034. },
  102035. enumerable: true,
  102036. configurable: true
  102037. });
  102038. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  102039. /**
  102040. * Gets the sprites render time capture status
  102041. */
  102042. get: function () {
  102043. return this._captureSpritesRenderTime;
  102044. },
  102045. /**
  102046. * Enable or disable the sprites render time capture
  102047. */
  102048. set: function (value) {
  102049. var _this = this;
  102050. if (value === this._captureSpritesRenderTime) {
  102051. return;
  102052. }
  102053. this._captureSpritesRenderTime = value;
  102054. if (value) {
  102055. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  102056. BABYLON.Tools.StartPerformanceCounter("Sprites");
  102057. _this._spritesRenderTime.beginMonitoring();
  102058. });
  102059. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  102060. BABYLON.Tools.EndPerformanceCounter("Sprites");
  102061. _this._spritesRenderTime.endMonitoring(false);
  102062. });
  102063. }
  102064. else {
  102065. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102066. this._onBeforeSpritesRenderingObserver = null;
  102067. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102068. this._onAfterSpritesRenderingObserver = null;
  102069. }
  102070. },
  102071. enumerable: true,
  102072. configurable: true
  102073. });
  102074. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  102075. /**
  102076. * Gets the perf counter used for physics time
  102077. */
  102078. get: function () {
  102079. return this._physicsTime;
  102080. },
  102081. enumerable: true,
  102082. configurable: true
  102083. });
  102084. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  102085. /**
  102086. * Gets the physics time capture status
  102087. */
  102088. get: function () {
  102089. return this._capturePhysicsTime;
  102090. },
  102091. /**
  102092. * Enable or disable the physics time capture
  102093. */
  102094. set: function (value) {
  102095. var _this = this;
  102096. if (value === this._capturePhysicsTime) {
  102097. return;
  102098. }
  102099. this._capturePhysicsTime = value;
  102100. if (value) {
  102101. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  102102. BABYLON.Tools.StartPerformanceCounter("Physics");
  102103. _this._physicsTime.beginMonitoring();
  102104. });
  102105. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  102106. BABYLON.Tools.EndPerformanceCounter("Physics");
  102107. _this._physicsTime.endMonitoring();
  102108. });
  102109. }
  102110. else {
  102111. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102112. this._onBeforePhysicsObserver = null;
  102113. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102114. this._onAfterPhysicsObserver = null;
  102115. }
  102116. },
  102117. enumerable: true,
  102118. configurable: true
  102119. });
  102120. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  102121. /**
  102122. * Gets the perf counter used for animations time
  102123. */
  102124. get: function () {
  102125. return this._animationsTime;
  102126. },
  102127. enumerable: true,
  102128. configurable: true
  102129. });
  102130. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  102131. /**
  102132. * Gets the animations time capture status
  102133. */
  102134. get: function () {
  102135. return this._captureAnimationsTime;
  102136. },
  102137. /**
  102138. * Enable or disable the animations time capture
  102139. */
  102140. set: function (value) {
  102141. var _this = this;
  102142. if (value === this._captureAnimationsTime) {
  102143. return;
  102144. }
  102145. this._captureAnimationsTime = value;
  102146. if (value) {
  102147. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  102148. _this._animationsTime.endMonitoring();
  102149. });
  102150. }
  102151. else {
  102152. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102153. this._onAfterAnimationsObserver = null;
  102154. }
  102155. },
  102156. enumerable: true,
  102157. configurable: true
  102158. });
  102159. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  102160. /**
  102161. * Gets the perf counter used for frame time capture
  102162. */
  102163. get: function () {
  102164. return this._frameTime;
  102165. },
  102166. enumerable: true,
  102167. configurable: true
  102168. });
  102169. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  102170. /**
  102171. * Gets the frame time capture status
  102172. */
  102173. get: function () {
  102174. return this._captureFrameTime;
  102175. },
  102176. /**
  102177. * Enable or disable the frame time capture
  102178. */
  102179. set: function (value) {
  102180. this._captureFrameTime = value;
  102181. },
  102182. enumerable: true,
  102183. configurable: true
  102184. });
  102185. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  102186. /**
  102187. * Gets the perf counter used for inter-frames time capture
  102188. */
  102189. get: function () {
  102190. return this._interFrameTime;
  102191. },
  102192. enumerable: true,
  102193. configurable: true
  102194. });
  102195. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  102196. /**
  102197. * Gets the inter-frames time capture status
  102198. */
  102199. get: function () {
  102200. return this._captureInterFrameTime;
  102201. },
  102202. /**
  102203. * Enable or disable the inter-frames time capture
  102204. */
  102205. set: function (value) {
  102206. this._captureInterFrameTime = value;
  102207. },
  102208. enumerable: true,
  102209. configurable: true
  102210. });
  102211. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  102212. /**
  102213. * Gets the perf counter used for render time capture
  102214. */
  102215. get: function () {
  102216. return this._renderTime;
  102217. },
  102218. enumerable: true,
  102219. configurable: true
  102220. });
  102221. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  102222. /**
  102223. * Gets the render time capture status
  102224. */
  102225. get: function () {
  102226. return this._captureRenderTime;
  102227. },
  102228. /**
  102229. * Enable or disable the render time capture
  102230. */
  102231. set: function (value) {
  102232. var _this = this;
  102233. if (value === this._captureRenderTime) {
  102234. return;
  102235. }
  102236. this._captureRenderTime = value;
  102237. if (value) {
  102238. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  102239. _this._renderTime.beginMonitoring();
  102240. BABYLON.Tools.StartPerformanceCounter("Main render");
  102241. });
  102242. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  102243. _this._renderTime.endMonitoring(false);
  102244. BABYLON.Tools.EndPerformanceCounter("Main render");
  102245. });
  102246. }
  102247. else {
  102248. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102249. this._onBeforeDrawPhaseObserver = null;
  102250. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102251. this._onAfterDrawPhaseObserver = null;
  102252. }
  102253. },
  102254. enumerable: true,
  102255. configurable: true
  102256. });
  102257. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  102258. /**
  102259. * Gets the perf counter used for camera render time capture
  102260. */
  102261. get: function () {
  102262. return this._cameraRenderTime;
  102263. },
  102264. enumerable: true,
  102265. configurable: true
  102266. });
  102267. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  102268. /**
  102269. * Gets the camera render time capture status
  102270. */
  102271. get: function () {
  102272. return this._captureCameraRenderTime;
  102273. },
  102274. /**
  102275. * Enable or disable the camera render time capture
  102276. */
  102277. set: function (value) {
  102278. var _this = this;
  102279. if (value === this._captureCameraRenderTime) {
  102280. return;
  102281. }
  102282. this._captureCameraRenderTime = value;
  102283. if (value) {
  102284. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  102285. _this._cameraRenderTime.beginMonitoring();
  102286. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  102287. });
  102288. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  102289. _this._cameraRenderTime.endMonitoring(false);
  102290. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  102291. });
  102292. }
  102293. else {
  102294. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102295. this._onBeforeCameraRenderObserver = null;
  102296. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102297. this._onAfterCameraRenderObserver = null;
  102298. }
  102299. },
  102300. enumerable: true,
  102301. configurable: true
  102302. });
  102303. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  102304. /**
  102305. * Gets the perf counter used for draw calls
  102306. */
  102307. get: function () {
  102308. return this.scene.getEngine()._drawCalls;
  102309. },
  102310. enumerable: true,
  102311. configurable: true
  102312. });
  102313. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  102314. /**
  102315. * Gets the perf counter used for texture collisions
  102316. */
  102317. get: function () {
  102318. return this.scene.getEngine()._textureCollisions;
  102319. },
  102320. enumerable: true,
  102321. configurable: true
  102322. });
  102323. SceneInstrumentation.prototype.dispose = function () {
  102324. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102325. this._onAfterRenderObserver = null;
  102326. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102327. this._onBeforeActiveMeshesEvaluationObserver = null;
  102328. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  102329. this._onAfterActiveMeshesEvaluationObserver = null;
  102330. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  102331. this._onBeforeRenderTargetsRenderObserver = null;
  102332. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  102333. this._onAfterRenderTargetsRenderObserver = null;
  102334. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  102335. this._onBeforeAnimationsObserver = null;
  102336. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102337. this._onBeforeParticlesRenderingObserver = null;
  102338. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102339. this._onAfterParticlesRenderingObserver = null;
  102340. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102341. this._onBeforeSpritesRenderingObserver = null;
  102342. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102343. this._onAfterSpritesRenderingObserver = null;
  102344. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102345. this._onBeforeDrawPhaseObserver = null;
  102346. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102347. this._onAfterDrawPhaseObserver = null;
  102348. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102349. this._onBeforePhysicsObserver = null;
  102350. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102351. this._onAfterPhysicsObserver = null;
  102352. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102353. this._onAfterAnimationsObserver = null;
  102354. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102355. this._onBeforeCameraRenderObserver = null;
  102356. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102357. this._onAfterCameraRenderObserver = null;
  102358. this.scene = null;
  102359. };
  102360. return SceneInstrumentation;
  102361. }());
  102362. BABYLON.SceneInstrumentation = SceneInstrumentation;
  102363. })(BABYLON || (BABYLON = {}));
  102364. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  102365. var BABYLON;
  102366. (function (BABYLON) {
  102367. /**
  102368. * @hidden
  102369. **/
  102370. var _TimeToken = /** @class */ (function () {
  102371. function _TimeToken() {
  102372. this._timeElapsedQueryEnded = false;
  102373. }
  102374. return _TimeToken;
  102375. }());
  102376. BABYLON._TimeToken = _TimeToken;
  102377. })(BABYLON || (BABYLON = {}));
  102378. //# sourceMappingURL=babylon.timeToken.js.map
  102379. var BABYLON;
  102380. (function (BABYLON) {
  102381. /**
  102382. * Background material defines definition.
  102383. * @hidden Mainly internal Use
  102384. */
  102385. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  102386. __extends(BackgroundMaterialDefines, _super);
  102387. /**
  102388. * Constructor of the defines.
  102389. */
  102390. function BackgroundMaterialDefines() {
  102391. var _this = _super.call(this) || this;
  102392. /**
  102393. * True if the diffuse texture is in use.
  102394. */
  102395. _this.DIFFUSE = false;
  102396. /**
  102397. * The direct UV channel to use.
  102398. */
  102399. _this.DIFFUSEDIRECTUV = 0;
  102400. /**
  102401. * True if the diffuse texture is in gamma space.
  102402. */
  102403. _this.GAMMADIFFUSE = false;
  102404. /**
  102405. * True if the diffuse texture has opacity in the alpha channel.
  102406. */
  102407. _this.DIFFUSEHASALPHA = false;
  102408. /**
  102409. * True if you want the material to fade to transparent at grazing angle.
  102410. */
  102411. _this.OPACITYFRESNEL = false;
  102412. /**
  102413. * True if an extra blur needs to be added in the reflection.
  102414. */
  102415. _this.REFLECTIONBLUR = false;
  102416. /**
  102417. * True if you want the material to fade to reflection at grazing angle.
  102418. */
  102419. _this.REFLECTIONFRESNEL = false;
  102420. /**
  102421. * True if you want the material to falloff as far as you move away from the scene center.
  102422. */
  102423. _this.REFLECTIONFALLOFF = false;
  102424. /**
  102425. * False if the current Webgl implementation does not support the texture lod extension.
  102426. */
  102427. _this.TEXTURELODSUPPORT = false;
  102428. /**
  102429. * True to ensure the data are premultiplied.
  102430. */
  102431. _this.PREMULTIPLYALPHA = false;
  102432. /**
  102433. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  102434. */
  102435. _this.USERGBCOLOR = false;
  102436. /**
  102437. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  102438. * stays aligned with the desired configuration.
  102439. */
  102440. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  102441. /**
  102442. * True to add noise in order to reduce the banding effect.
  102443. */
  102444. _this.NOISE = false;
  102445. /**
  102446. * is the reflection texture in BGR color scheme?
  102447. * Mainly used to solve a bug in ios10 video tag
  102448. */
  102449. _this.REFLECTIONBGR = false;
  102450. _this.IMAGEPROCESSING = false;
  102451. _this.VIGNETTE = false;
  102452. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  102453. _this.VIGNETTEBLENDMODEOPAQUE = false;
  102454. _this.TONEMAPPING = false;
  102455. _this.CONTRAST = false;
  102456. _this.COLORCURVES = false;
  102457. _this.COLORGRADING = false;
  102458. _this.COLORGRADING3D = false;
  102459. _this.SAMPLER3DGREENDEPTH = false;
  102460. _this.SAMPLER3DBGRMAP = false;
  102461. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  102462. _this.EXPOSURE = false;
  102463. // Reflection.
  102464. _this.REFLECTION = false;
  102465. _this.REFLECTIONMAP_3D = false;
  102466. _this.REFLECTIONMAP_SPHERICAL = false;
  102467. _this.REFLECTIONMAP_PLANAR = false;
  102468. _this.REFLECTIONMAP_CUBIC = false;
  102469. _this.REFLECTIONMAP_PROJECTION = false;
  102470. _this.REFLECTIONMAP_SKYBOX = false;
  102471. _this.REFLECTIONMAP_EXPLICIT = false;
  102472. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102473. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102474. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102475. _this.INVERTCUBICMAP = false;
  102476. _this.REFLECTIONMAP_OPPOSITEZ = false;
  102477. _this.LODINREFLECTIONALPHA = false;
  102478. _this.GAMMAREFLECTION = false;
  102479. _this.RGBDREFLECTION = false;
  102480. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  102481. // Default BJS.
  102482. _this.MAINUV1 = false;
  102483. _this.MAINUV2 = false;
  102484. _this.UV1 = false;
  102485. _this.UV2 = false;
  102486. _this.CLIPPLANE = false;
  102487. _this.POINTSIZE = false;
  102488. _this.FOG = false;
  102489. _this.NORMAL = false;
  102490. _this.NUM_BONE_INFLUENCERS = 0;
  102491. _this.BonesPerMesh = 0;
  102492. _this.INSTANCES = false;
  102493. _this.SHADOWFLOAT = false;
  102494. _this.rebuild();
  102495. return _this;
  102496. }
  102497. return BackgroundMaterialDefines;
  102498. }(BABYLON.MaterialDefines));
  102499. /**
  102500. * Background material used to create an efficient environement around your scene.
  102501. */
  102502. var BackgroundMaterial = /** @class */ (function (_super) {
  102503. __extends(BackgroundMaterial, _super);
  102504. /**
  102505. * Instantiates a Background Material in the given scene
  102506. * @param name The friendly name of the material
  102507. * @param scene The scene to add the material to
  102508. */
  102509. function BackgroundMaterial(name, scene) {
  102510. var _this = _super.call(this, name, scene) || this;
  102511. /**
  102512. * Key light Color (multiply against the environement texture)
  102513. */
  102514. _this.primaryColor = BABYLON.Color3.White();
  102515. _this._primaryColorShadowLevel = 0;
  102516. _this._primaryColorHighlightLevel = 0;
  102517. /**
  102518. * Reflection Texture used in the material.
  102519. * Should be author in a specific way for the best result (refer to the documentation).
  102520. */
  102521. _this.reflectionTexture = null;
  102522. /**
  102523. * Reflection Texture level of blur.
  102524. *
  102525. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  102526. * texture twice.
  102527. */
  102528. _this.reflectionBlur = 0;
  102529. /**
  102530. * Diffuse Texture used in the material.
  102531. * Should be author in a specific way for the best result (refer to the documentation).
  102532. */
  102533. _this.diffuseTexture = null;
  102534. _this._shadowLights = null;
  102535. /**
  102536. * Specify the list of lights casting shadow on the material.
  102537. * All scene shadow lights will be included if null.
  102538. */
  102539. _this.shadowLights = null;
  102540. /**
  102541. * Helps adjusting the shadow to a softer level if required.
  102542. * 0 means black shadows and 1 means no shadows.
  102543. */
  102544. _this.shadowLevel = 0;
  102545. /**
  102546. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  102547. * It is usually zero but might be interesting to modify according to your setup.
  102548. */
  102549. _this.sceneCenter = BABYLON.Vector3.Zero();
  102550. /**
  102551. * This helps specifying that the material is falling off to the sky box at grazing angle.
  102552. * This helps ensuring a nice transition when the camera goes under the ground.
  102553. */
  102554. _this.opacityFresnel = true;
  102555. /**
  102556. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  102557. * This helps adding a mirror texture on the ground.
  102558. */
  102559. _this.reflectionFresnel = false;
  102560. /**
  102561. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  102562. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  102563. */
  102564. _this.reflectionFalloffDistance = 0.0;
  102565. /**
  102566. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  102567. */
  102568. _this.reflectionAmount = 1.0;
  102569. /**
  102570. * This specifies the weight of the reflection at grazing angle.
  102571. */
  102572. _this.reflectionReflectance0 = 0.05;
  102573. /**
  102574. * This specifies the weight of the reflection at a perpendicular point of view.
  102575. */
  102576. _this.reflectionReflectance90 = 0.5;
  102577. /**
  102578. * Helps to directly use the maps channels instead of their level.
  102579. */
  102580. _this.useRGBColor = true;
  102581. /**
  102582. * This helps reducing the banding effect that could occur on the background.
  102583. */
  102584. _this.enableNoise = false;
  102585. _this._fovMultiplier = 1.0;
  102586. /**
  102587. * Enable the FOV adjustment feature controlled by fovMultiplier.
  102588. */
  102589. _this.useEquirectangularFOV = false;
  102590. _this._maxSimultaneousLights = 4;
  102591. /**
  102592. * Number of Simultaneous lights allowed on the material.
  102593. */
  102594. _this.maxSimultaneousLights = 4;
  102595. /**
  102596. * Keep track of the image processing observer to allow dispose and replace.
  102597. */
  102598. _this._imageProcessingObserver = null;
  102599. /**
  102600. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  102601. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  102602. */
  102603. _this.switchToBGR = false;
  102604. // Temp values kept as cache in the material.
  102605. _this._renderTargets = new BABYLON.SmartArray(16);
  102606. _this._reflectionControls = BABYLON.Vector4.Zero();
  102607. _this._white = BABYLON.Color3.White();
  102608. _this._primaryShadowColor = BABYLON.Color3.Black();
  102609. _this._primaryHighlightColor = BABYLON.Color3.Black();
  102610. // Setup the default processing configuration to the scene.
  102611. _this._attachImageProcessingConfiguration(null);
  102612. _this.getRenderTargetTextures = function () {
  102613. _this._renderTargets.reset();
  102614. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  102615. _this._renderTargets.push(_this._diffuseTexture);
  102616. }
  102617. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  102618. _this._renderTargets.push(_this._reflectionTexture);
  102619. }
  102620. return _this._renderTargets;
  102621. };
  102622. return _this;
  102623. }
  102624. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  102625. /**
  102626. * Experimental Internal Use Only.
  102627. *
  102628. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  102629. * This acts as a helper to set the primary color to a more "human friendly" value.
  102630. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  102631. * output color as close as possible from the chosen value.
  102632. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  102633. * part of lighting setup.)
  102634. */
  102635. get: function () {
  102636. return this.__perceptualColor;
  102637. },
  102638. set: function (value) {
  102639. this.__perceptualColor = value;
  102640. this._computePrimaryColorFromPerceptualColor();
  102641. this._markAllSubMeshesAsLightsDirty();
  102642. },
  102643. enumerable: true,
  102644. configurable: true
  102645. });
  102646. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  102647. /**
  102648. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  102649. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  102650. */
  102651. get: function () {
  102652. return this._primaryColorShadowLevel;
  102653. },
  102654. set: function (value) {
  102655. this._primaryColorShadowLevel = value;
  102656. this._computePrimaryColors();
  102657. this._markAllSubMeshesAsLightsDirty();
  102658. },
  102659. enumerable: true,
  102660. configurable: true
  102661. });
  102662. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  102663. /**
  102664. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  102665. * The primary color is used at the level chosen to define what the white area would look.
  102666. */
  102667. get: function () {
  102668. return this._primaryColorHighlightLevel;
  102669. },
  102670. set: function (value) {
  102671. this._primaryColorHighlightLevel = value;
  102672. this._computePrimaryColors();
  102673. this._markAllSubMeshesAsLightsDirty();
  102674. },
  102675. enumerable: true,
  102676. configurable: true
  102677. });
  102678. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  102679. /**
  102680. * Sets the reflection reflectance fresnel values according to the default standard
  102681. * empirically know to work well :-)
  102682. */
  102683. set: function (value) {
  102684. var reflectionWeight = value;
  102685. if (reflectionWeight < 0.5) {
  102686. reflectionWeight = reflectionWeight * 2.0;
  102687. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  102688. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  102689. }
  102690. else {
  102691. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  102692. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  102693. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  102694. }
  102695. },
  102696. enumerable: true,
  102697. configurable: true
  102698. });
  102699. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  102700. /**
  102701. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102702. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  102703. * Recommended to be keep at 1.0 except for special cases.
  102704. */
  102705. get: function () {
  102706. return this._fovMultiplier;
  102707. },
  102708. set: function (value) {
  102709. if (isNaN(value)) {
  102710. value = 1.0;
  102711. }
  102712. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  102713. },
  102714. enumerable: true,
  102715. configurable: true
  102716. });
  102717. /**
  102718. * Attaches a new image processing configuration to the PBR Material.
  102719. * @param configuration (if null the scene configuration will be use)
  102720. */
  102721. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  102722. var _this = this;
  102723. if (configuration === this._imageProcessingConfiguration) {
  102724. return;
  102725. }
  102726. // Detaches observer.
  102727. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102728. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102729. }
  102730. // Pick the scene configuration if needed.
  102731. if (!configuration) {
  102732. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  102733. }
  102734. else {
  102735. this._imageProcessingConfiguration = configuration;
  102736. }
  102737. // Attaches observer.
  102738. if (this._imageProcessingConfiguration) {
  102739. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  102740. _this._computePrimaryColorFromPerceptualColor();
  102741. _this._markAllSubMeshesAsImageProcessingDirty();
  102742. });
  102743. }
  102744. };
  102745. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  102746. /**
  102747. * Gets the image processing configuration used either in this material.
  102748. */
  102749. get: function () {
  102750. return this._imageProcessingConfiguration;
  102751. },
  102752. /**
  102753. * Sets the Default image processing configuration used either in the this material.
  102754. *
  102755. * If sets to null, the scene one is in use.
  102756. */
  102757. set: function (value) {
  102758. this._attachImageProcessingConfiguration(value);
  102759. // Ensure the effect will be rebuilt.
  102760. this._markAllSubMeshesAsTexturesDirty();
  102761. },
  102762. enumerable: true,
  102763. configurable: true
  102764. });
  102765. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  102766. /**
  102767. * Gets wether the color curves effect is enabled.
  102768. */
  102769. get: function () {
  102770. return this.imageProcessingConfiguration.colorCurvesEnabled;
  102771. },
  102772. /**
  102773. * Sets wether the color curves effect is enabled.
  102774. */
  102775. set: function (value) {
  102776. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  102777. },
  102778. enumerable: true,
  102779. configurable: true
  102780. });
  102781. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  102782. /**
  102783. * Gets wether the color grading effect is enabled.
  102784. */
  102785. get: function () {
  102786. return this.imageProcessingConfiguration.colorGradingEnabled;
  102787. },
  102788. /**
  102789. * Gets wether the color grading effect is enabled.
  102790. */
  102791. set: function (value) {
  102792. this.imageProcessingConfiguration.colorGradingEnabled = value;
  102793. },
  102794. enumerable: true,
  102795. configurable: true
  102796. });
  102797. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  102798. /**
  102799. * Gets wether tonemapping is enabled or not.
  102800. */
  102801. get: function () {
  102802. return this._imageProcessingConfiguration.toneMappingEnabled;
  102803. },
  102804. /**
  102805. * Sets wether tonemapping is enabled or not
  102806. */
  102807. set: function (value) {
  102808. this._imageProcessingConfiguration.toneMappingEnabled = value;
  102809. },
  102810. enumerable: true,
  102811. configurable: true
  102812. });
  102813. ;
  102814. ;
  102815. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  102816. /**
  102817. * The camera exposure used on this material.
  102818. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102819. * This corresponds to a photographic exposure.
  102820. */
  102821. get: function () {
  102822. return this._imageProcessingConfiguration.exposure;
  102823. },
  102824. /**
  102825. * The camera exposure used on this material.
  102826. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102827. * This corresponds to a photographic exposure.
  102828. */
  102829. set: function (value) {
  102830. this._imageProcessingConfiguration.exposure = value;
  102831. },
  102832. enumerable: true,
  102833. configurable: true
  102834. });
  102835. ;
  102836. ;
  102837. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  102838. /**
  102839. * Gets The camera contrast used on this material.
  102840. */
  102841. get: function () {
  102842. return this._imageProcessingConfiguration.contrast;
  102843. },
  102844. /**
  102845. * Sets The camera contrast used on this material.
  102846. */
  102847. set: function (value) {
  102848. this._imageProcessingConfiguration.contrast = value;
  102849. },
  102850. enumerable: true,
  102851. configurable: true
  102852. });
  102853. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  102854. /**
  102855. * Gets the Color Grading 2D Lookup Texture.
  102856. */
  102857. get: function () {
  102858. return this._imageProcessingConfiguration.colorGradingTexture;
  102859. },
  102860. /**
  102861. * Sets the Color Grading 2D Lookup Texture.
  102862. */
  102863. set: function (value) {
  102864. this.imageProcessingConfiguration.colorGradingTexture = value;
  102865. },
  102866. enumerable: true,
  102867. configurable: true
  102868. });
  102869. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  102870. /**
  102871. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102872. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102873. * 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;
  102874. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102875. */
  102876. get: function () {
  102877. return this.imageProcessingConfiguration.colorCurves;
  102878. },
  102879. /**
  102880. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102881. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102882. * 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;
  102883. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102884. */
  102885. set: function (value) {
  102886. this.imageProcessingConfiguration.colorCurves = value;
  102887. },
  102888. enumerable: true,
  102889. configurable: true
  102890. });
  102891. /**
  102892. * The entire material has been created in order to prevent overdraw.
  102893. * @returns false
  102894. */
  102895. BackgroundMaterial.prototype.needAlphaTesting = function () {
  102896. return true;
  102897. };
  102898. /**
  102899. * The entire material has been created in order to prevent overdraw.
  102900. * @returns true if blending is enable
  102901. */
  102902. BackgroundMaterial.prototype.needAlphaBlending = function () {
  102903. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  102904. };
  102905. /**
  102906. * Checks wether the material is ready to be rendered for a given mesh.
  102907. * @param mesh The mesh to render
  102908. * @param subMesh The submesh to check against
  102909. * @param useInstances Specify wether or not the material is used with instances
  102910. * @returns true if all the dependencies are ready (Textures, Effects...)
  102911. */
  102912. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  102913. var _this = this;
  102914. if (useInstances === void 0) { useInstances = false; }
  102915. if (subMesh.effect && this.isFrozen) {
  102916. if (this._wasPreviouslyReady) {
  102917. return true;
  102918. }
  102919. }
  102920. if (!subMesh._materialDefines) {
  102921. subMesh._materialDefines = new BackgroundMaterialDefines();
  102922. }
  102923. var scene = this.getScene();
  102924. var defines = subMesh._materialDefines;
  102925. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  102926. if (defines._renderId === scene.getRenderId()) {
  102927. return true;
  102928. }
  102929. }
  102930. var engine = scene.getEngine();
  102931. // Lights
  102932. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  102933. defines._needNormals = true;
  102934. // Textures
  102935. if (defines._areTexturesDirty) {
  102936. defines._needUVs = false;
  102937. if (scene.texturesEnabled) {
  102938. if (scene.getEngine().getCaps().textureLOD) {
  102939. defines.TEXTURELODSUPPORT = true;
  102940. }
  102941. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102942. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  102943. return false;
  102944. }
  102945. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  102946. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  102947. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  102948. defines.OPACITYFRESNEL = this._opacityFresnel;
  102949. }
  102950. else {
  102951. defines.DIFFUSE = false;
  102952. defines.DIFFUSEHASALPHA = false;
  102953. defines.GAMMADIFFUSE = false;
  102954. defines.OPACITYFRESNEL = false;
  102955. }
  102956. var reflectionTexture = this._reflectionTexture;
  102957. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102958. if (!reflectionTexture.isReadyOrNotBlocking()) {
  102959. return false;
  102960. }
  102961. defines.REFLECTION = true;
  102962. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  102963. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  102964. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  102965. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  102966. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  102967. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  102968. defines.REFLECTIONBGR = this.switchToBGR;
  102969. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  102970. defines.INVERTCUBICMAP = true;
  102971. }
  102972. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  102973. switch (reflectionTexture.coordinatesMode) {
  102974. case BABYLON.Texture.EXPLICIT_MODE:
  102975. defines.REFLECTIONMAP_EXPLICIT = true;
  102976. break;
  102977. case BABYLON.Texture.PLANAR_MODE:
  102978. defines.REFLECTIONMAP_PLANAR = true;
  102979. break;
  102980. case BABYLON.Texture.PROJECTION_MODE:
  102981. defines.REFLECTIONMAP_PROJECTION = true;
  102982. break;
  102983. case BABYLON.Texture.SKYBOX_MODE:
  102984. defines.REFLECTIONMAP_SKYBOX = true;
  102985. break;
  102986. case BABYLON.Texture.SPHERICAL_MODE:
  102987. defines.REFLECTIONMAP_SPHERICAL = true;
  102988. break;
  102989. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  102990. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  102991. break;
  102992. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  102993. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  102994. break;
  102995. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  102996. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  102997. break;
  102998. case BABYLON.Texture.CUBIC_MODE:
  102999. case BABYLON.Texture.INVCUBIC_MODE:
  103000. default:
  103001. defines.REFLECTIONMAP_CUBIC = true;
  103002. break;
  103003. }
  103004. if (this.reflectionFresnel) {
  103005. defines.REFLECTIONFRESNEL = true;
  103006. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  103007. this._reflectionControls.x = this.reflectionAmount;
  103008. this._reflectionControls.y = this.reflectionReflectance0;
  103009. this._reflectionControls.z = this.reflectionReflectance90;
  103010. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  103011. }
  103012. else {
  103013. defines.REFLECTIONFRESNEL = false;
  103014. defines.REFLECTIONFALLOFF = false;
  103015. }
  103016. }
  103017. else {
  103018. defines.REFLECTION = false;
  103019. defines.REFLECTIONFRESNEL = false;
  103020. defines.REFLECTIONFALLOFF = false;
  103021. defines.REFLECTIONBLUR = false;
  103022. defines.REFLECTIONMAP_3D = false;
  103023. defines.REFLECTIONMAP_SPHERICAL = false;
  103024. defines.REFLECTIONMAP_PLANAR = false;
  103025. defines.REFLECTIONMAP_CUBIC = false;
  103026. defines.REFLECTIONMAP_PROJECTION = false;
  103027. defines.REFLECTIONMAP_SKYBOX = false;
  103028. defines.REFLECTIONMAP_EXPLICIT = false;
  103029. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  103030. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  103031. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  103032. defines.INVERTCUBICMAP = false;
  103033. defines.REFLECTIONMAP_OPPOSITEZ = false;
  103034. defines.LODINREFLECTIONALPHA = false;
  103035. defines.GAMMAREFLECTION = false;
  103036. defines.RGBDREFLECTION = false;
  103037. }
  103038. }
  103039. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  103040. defines.USERGBCOLOR = this._useRGBColor;
  103041. defines.NOISE = this._enableNoise;
  103042. }
  103043. if (defines._areLightsDirty) {
  103044. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  103045. }
  103046. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  103047. if (!this._imageProcessingConfiguration.isReady()) {
  103048. return false;
  103049. }
  103050. this._imageProcessingConfiguration.prepareDefines(defines);
  103051. }
  103052. // Misc.
  103053. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  103054. // Values that need to be evaluated on every frame
  103055. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  103056. // Attribs
  103057. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  103058. if (mesh) {
  103059. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  103060. mesh.createNormals(true);
  103061. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  103062. }
  103063. }
  103064. }
  103065. // Get correct effect
  103066. if (defines.isDirty) {
  103067. defines.markAsProcessed();
  103068. scene.resetCachedMaterial();
  103069. // Fallbacks
  103070. var fallbacks = new BABYLON.EffectFallbacks();
  103071. if (defines.FOG) {
  103072. fallbacks.addFallback(0, "FOG");
  103073. }
  103074. if (defines.POINTSIZE) {
  103075. fallbacks.addFallback(1, "POINTSIZE");
  103076. }
  103077. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  103078. if (defines.NUM_BONE_INFLUENCERS > 0) {
  103079. fallbacks.addCPUSkinningFallback(0, mesh);
  103080. }
  103081. //Attributes
  103082. var attribs = [BABYLON.VertexBuffer.PositionKind];
  103083. if (defines.NORMAL) {
  103084. attribs.push(BABYLON.VertexBuffer.NormalKind);
  103085. }
  103086. if (defines.UV1) {
  103087. attribs.push(BABYLON.VertexBuffer.UVKind);
  103088. }
  103089. if (defines.UV2) {
  103090. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  103091. }
  103092. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  103093. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  103094. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  103095. "vFogInfos", "vFogColor", "pointSize",
  103096. "vClipPlane", "mBones",
  103097. "vPrimaryColor", "vPrimaryColorShadow",
  103098. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  103099. "shadowLevel", "alpha",
  103100. "vBackgroundCenter", "vReflectionControl",
  103101. "vDiffuseInfos", "diffuseMatrix",
  103102. ];
  103103. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  103104. var uniformBuffers = ["Material", "Scene"];
  103105. if (BABYLON.ImageProcessingConfiguration) {
  103106. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  103107. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  103108. }
  103109. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  103110. uniformsNames: uniforms,
  103111. uniformBuffersNames: uniformBuffers,
  103112. samplers: samplers,
  103113. defines: defines,
  103114. maxSimultaneousLights: this._maxSimultaneousLights
  103115. });
  103116. var onCompiled = function (effect) {
  103117. if (_this.onCompiled) {
  103118. _this.onCompiled(effect);
  103119. }
  103120. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  103121. };
  103122. var join = defines.toString();
  103123. subMesh.setEffect(scene.getEngine().createEffect("background", {
  103124. attributes: attribs,
  103125. uniformsNames: uniforms,
  103126. uniformBuffersNames: uniformBuffers,
  103127. samplers: samplers,
  103128. defines: join,
  103129. fallbacks: fallbacks,
  103130. onCompiled: onCompiled,
  103131. onError: this.onError,
  103132. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  103133. }, engine), defines);
  103134. this.buildUniformLayout();
  103135. }
  103136. if (!subMesh.effect || !subMesh.effect.isReady()) {
  103137. return false;
  103138. }
  103139. defines._renderId = scene.getRenderId();
  103140. this._wasPreviouslyReady = true;
  103141. return true;
  103142. };
  103143. /**
  103144. * Compute the primary color according to the chosen perceptual color.
  103145. */
  103146. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  103147. if (!this.__perceptualColor) {
  103148. return;
  103149. }
  103150. this._primaryColor.copyFrom(this.__perceptualColor);
  103151. // Revert gamma space.
  103152. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  103153. // Revert image processing configuration.
  103154. if (this._imageProcessingConfiguration) {
  103155. // Revert Exposure.
  103156. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  103157. }
  103158. this._computePrimaryColors();
  103159. };
  103160. /**
  103161. * Compute the highlights and shadow colors according to their chosen levels.
  103162. */
  103163. BackgroundMaterial.prototype._computePrimaryColors = function () {
  103164. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  103165. return;
  103166. }
  103167. // Find the highlight color based on the configuration.
  103168. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  103169. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  103170. // Find the shadow color based on the configuration.
  103171. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  103172. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  103173. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  103174. };
  103175. /**
  103176. * Build the uniform buffer used in the material.
  103177. */
  103178. BackgroundMaterial.prototype.buildUniformLayout = function () {
  103179. // Order is important !
  103180. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  103181. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  103182. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  103183. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  103184. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  103185. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  103186. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  103187. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  103188. this._uniformBuffer.addUniform("pointSize", 1);
  103189. this._uniformBuffer.addUniform("shadowLevel", 1);
  103190. this._uniformBuffer.addUniform("alpha", 1);
  103191. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  103192. this._uniformBuffer.addUniform("vReflectionControl", 4);
  103193. this._uniformBuffer.create();
  103194. };
  103195. /**
  103196. * Unbind the material.
  103197. */
  103198. BackgroundMaterial.prototype.unbind = function () {
  103199. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  103200. this._uniformBuffer.setTexture("diffuseSampler", null);
  103201. }
  103202. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  103203. this._uniformBuffer.setTexture("reflectionSampler", null);
  103204. }
  103205. _super.prototype.unbind.call(this);
  103206. };
  103207. /**
  103208. * Bind only the world matrix to the material.
  103209. * @param world The world matrix to bind.
  103210. */
  103211. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  103212. this._activeEffect.setMatrix("world", world);
  103213. };
  103214. /**
  103215. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  103216. * @param world The world matrix to bind.
  103217. * @param subMesh The submesh to bind for.
  103218. */
  103219. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  103220. var scene = this.getScene();
  103221. var defines = subMesh._materialDefines;
  103222. if (!defines) {
  103223. return;
  103224. }
  103225. var effect = subMesh.effect;
  103226. if (!effect) {
  103227. return;
  103228. }
  103229. this._activeEffect = effect;
  103230. // Matrices
  103231. this.bindOnlyWorldMatrix(world);
  103232. // Bones
  103233. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  103234. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  103235. if (mustRebind) {
  103236. this._uniformBuffer.bindToEffect(effect, "Material");
  103237. this.bindViewProjection(effect);
  103238. var reflectionTexture = this._reflectionTexture;
  103239. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  103240. // Texture uniforms
  103241. if (scene.texturesEnabled) {
  103242. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103243. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  103244. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  103245. }
  103246. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103247. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  103248. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  103249. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  103250. }
  103251. }
  103252. if (this.shadowLevel > 0) {
  103253. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  103254. }
  103255. this._uniformBuffer.updateFloat("alpha", this.alpha);
  103256. // Point size
  103257. if (this.pointsCloud) {
  103258. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  103259. }
  103260. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  103261. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  103262. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  103263. }
  103264. else {
  103265. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  103266. }
  103267. }
  103268. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  103269. // Textures
  103270. if (scene.texturesEnabled) {
  103271. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103272. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  103273. }
  103274. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103275. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  103276. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103277. }
  103278. else if (!defines.REFLECTIONBLUR) {
  103279. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103280. }
  103281. else {
  103282. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  103283. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  103284. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  103285. }
  103286. if (defines.REFLECTIONFRESNEL) {
  103287. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  103288. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  103289. }
  103290. }
  103291. }
  103292. // Clip plane
  103293. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  103294. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  103295. }
  103296. if (mustRebind || !this.isFrozen) {
  103297. if (scene.lightsEnabled) {
  103298. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  103299. }
  103300. // View
  103301. this.bindView(effect);
  103302. // Fog
  103303. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  103304. // image processing
  103305. if (this._imageProcessingConfiguration) {
  103306. this._imageProcessingConfiguration.bind(this._activeEffect);
  103307. }
  103308. }
  103309. this._uniformBuffer.update();
  103310. this._afterBind(mesh, this._activeEffect);
  103311. };
  103312. /**
  103313. * Dispose the material.
  103314. * @param forceDisposeEffect Force disposal of the associated effect.
  103315. * @param forceDisposeTextures Force disposal of the associated textures.
  103316. */
  103317. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  103318. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  103319. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  103320. if (forceDisposeTextures) {
  103321. if (this.diffuseTexture) {
  103322. this.diffuseTexture.dispose();
  103323. }
  103324. if (this.reflectionTexture) {
  103325. this.reflectionTexture.dispose();
  103326. }
  103327. }
  103328. this._renderTargets.dispose();
  103329. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103330. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103331. }
  103332. _super.prototype.dispose.call(this, forceDisposeEffect);
  103333. };
  103334. /**
  103335. * Clones the material.
  103336. * @param name The cloned name.
  103337. * @returns The cloned material.
  103338. */
  103339. BackgroundMaterial.prototype.clone = function (name) {
  103340. var _this = this;
  103341. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  103342. };
  103343. /**
  103344. * Serializes the current material to its JSON representation.
  103345. * @returns The JSON representation.
  103346. */
  103347. BackgroundMaterial.prototype.serialize = function () {
  103348. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103349. serializationObject.customType = "BABYLON.BackgroundMaterial";
  103350. return serializationObject;
  103351. };
  103352. /**
  103353. * Gets the class name of the material
  103354. * @returns "BackgroundMaterial"
  103355. */
  103356. BackgroundMaterial.prototype.getClassName = function () {
  103357. return "BackgroundMaterial";
  103358. };
  103359. /**
  103360. * Parse a JSON input to create back a background material.
  103361. * @param source The JSON data to parse
  103362. * @param scene The scene to create the parsed material in
  103363. * @param rootUrl The root url of the assets the material depends upon
  103364. * @returns the instantiated BackgroundMaterial.
  103365. */
  103366. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  103367. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  103368. };
  103369. /**
  103370. * Standard reflectance value at parallel view angle.
  103371. */
  103372. BackgroundMaterial.StandardReflectance0 = 0.05;
  103373. /**
  103374. * Standard reflectance value at grazing angle.
  103375. */
  103376. BackgroundMaterial.StandardReflectance90 = 0.5;
  103377. __decorate([
  103378. BABYLON.serializeAsColor3()
  103379. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  103380. __decorate([
  103381. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103382. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  103383. __decorate([
  103384. BABYLON.serializeAsColor3()
  103385. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  103386. __decorate([
  103387. BABYLON.serialize()
  103388. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  103389. __decorate([
  103390. BABYLON.serialize()
  103391. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  103392. __decorate([
  103393. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103394. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  103395. __decorate([
  103396. BABYLON.serializeAsTexture()
  103397. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  103398. __decorate([
  103399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103400. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  103401. __decorate([
  103402. BABYLON.serialize()
  103403. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  103404. __decorate([
  103405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103406. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  103407. __decorate([
  103408. BABYLON.serializeAsTexture()
  103409. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  103410. __decorate([
  103411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103412. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  103413. __decorate([
  103414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103415. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  103416. __decorate([
  103417. BABYLON.serialize()
  103418. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  103419. __decorate([
  103420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103421. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  103422. __decorate([
  103423. BABYLON.serializeAsVector3()
  103424. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  103425. __decorate([
  103426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103427. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  103428. __decorate([
  103429. BABYLON.serialize()
  103430. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  103431. __decorate([
  103432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103433. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  103434. __decorate([
  103435. BABYLON.serialize()
  103436. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  103437. __decorate([
  103438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103439. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  103440. __decorate([
  103441. BABYLON.serialize()
  103442. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  103443. __decorate([
  103444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103445. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  103446. __decorate([
  103447. BABYLON.serialize()
  103448. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  103449. __decorate([
  103450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103451. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  103452. __decorate([
  103453. BABYLON.serialize()
  103454. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  103455. __decorate([
  103456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103457. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  103458. __decorate([
  103459. BABYLON.serialize()
  103460. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  103461. __decorate([
  103462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103463. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  103464. __decorate([
  103465. BABYLON.serialize()
  103466. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  103467. __decorate([
  103468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103469. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  103470. __decorate([
  103471. BABYLON.serialize()
  103472. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  103473. __decorate([
  103474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103475. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  103476. __decorate([
  103477. BABYLON.serialize()
  103478. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  103479. __decorate([
  103480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103481. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  103482. __decorate([
  103483. BABYLON.serializeAsImageProcessingConfiguration()
  103484. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  103485. return BackgroundMaterial;
  103486. }(BABYLON.PushMaterial));
  103487. BABYLON.BackgroundMaterial = BackgroundMaterial;
  103488. })(BABYLON || (BABYLON = {}));
  103489. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  103490. var __assign = (this && this.__assign) || Object.assign || function(t) {
  103491. for (var s, i = 1, n = arguments.length; i < n; i++) {
  103492. s = arguments[i];
  103493. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  103494. t[p] = s[p];
  103495. }
  103496. return t;
  103497. };
  103498. var BABYLON;
  103499. (function (BABYLON) {
  103500. /**
  103501. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  103502. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  103503. * It also helps with the default setup of your imageProcessing configuration.
  103504. */
  103505. var EnvironmentHelper = /** @class */ (function () {
  103506. /**
  103507. * constructor
  103508. * @param options
  103509. * @param scene The scene to add the material to
  103510. */
  103511. function EnvironmentHelper(options, scene) {
  103512. var _this = this;
  103513. this._errorHandler = function (message, exception) {
  103514. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  103515. };
  103516. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  103517. this._scene = scene;
  103518. this.onErrorObservable = new BABYLON.Observable();
  103519. this._setupBackground();
  103520. this._setupImageProcessing();
  103521. }
  103522. /**
  103523. * Creates the default options for the helper.
  103524. */
  103525. EnvironmentHelper._getDefaultOptions = function () {
  103526. return {
  103527. createGround: true,
  103528. groundSize: 15,
  103529. groundTexture: this._groundTextureCDNUrl,
  103530. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103531. groundOpacity: 0.9,
  103532. enableGroundShadow: true,
  103533. groundShadowLevel: 0.5,
  103534. enableGroundMirror: false,
  103535. groundMirrorSizeRatio: 0.3,
  103536. groundMirrorBlurKernel: 64,
  103537. groundMirrorAmount: 1,
  103538. groundMirrorFresnelWeight: 1,
  103539. groundMirrorFallOffDistance: 0,
  103540. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  103541. groundYBias: 0.00001,
  103542. createSkybox: true,
  103543. skyboxSize: 20,
  103544. skyboxTexture: this._skyboxTextureCDNUrl,
  103545. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103546. backgroundYRotation: 0,
  103547. sizeAuto: true,
  103548. rootPosition: BABYLON.Vector3.Zero(),
  103549. setupImageProcessing: true,
  103550. environmentTexture: this._environmentTextureCDNUrl,
  103551. cameraExposure: 0.8,
  103552. cameraContrast: 1.2,
  103553. toneMappingEnabled: true,
  103554. };
  103555. };
  103556. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  103557. /**
  103558. * Gets the root mesh created by the helper.
  103559. */
  103560. get: function () {
  103561. return this._rootMesh;
  103562. },
  103563. enumerable: true,
  103564. configurable: true
  103565. });
  103566. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  103567. /**
  103568. * Gets the skybox created by the helper.
  103569. */
  103570. get: function () {
  103571. return this._skybox;
  103572. },
  103573. enumerable: true,
  103574. configurable: true
  103575. });
  103576. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  103577. /**
  103578. * Gets the skybox texture created by the helper.
  103579. */
  103580. get: function () {
  103581. return this._skyboxTexture;
  103582. },
  103583. enumerable: true,
  103584. configurable: true
  103585. });
  103586. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  103587. /**
  103588. * Gets the skybox material created by the helper.
  103589. */
  103590. get: function () {
  103591. return this._skyboxMaterial;
  103592. },
  103593. enumerable: true,
  103594. configurable: true
  103595. });
  103596. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  103597. /**
  103598. * Gets the ground mesh created by the helper.
  103599. */
  103600. get: function () {
  103601. return this._ground;
  103602. },
  103603. enumerable: true,
  103604. configurable: true
  103605. });
  103606. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  103607. /**
  103608. * Gets the ground texture created by the helper.
  103609. */
  103610. get: function () {
  103611. return this._groundTexture;
  103612. },
  103613. enumerable: true,
  103614. configurable: true
  103615. });
  103616. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  103617. /**
  103618. * Gets the ground mirror created by the helper.
  103619. */
  103620. get: function () {
  103621. return this._groundMirror;
  103622. },
  103623. enumerable: true,
  103624. configurable: true
  103625. });
  103626. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  103627. /**
  103628. * Gets the ground mirror render list to helps pushing the meshes
  103629. * you wish in the ground reflection.
  103630. */
  103631. get: function () {
  103632. if (this._groundMirror) {
  103633. return this._groundMirror.renderList;
  103634. }
  103635. return null;
  103636. },
  103637. enumerable: true,
  103638. configurable: true
  103639. });
  103640. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  103641. /**
  103642. * Gets the ground material created by the helper.
  103643. */
  103644. get: function () {
  103645. return this._groundMaterial;
  103646. },
  103647. enumerable: true,
  103648. configurable: true
  103649. });
  103650. /**
  103651. * Updates the background according to the new options
  103652. * @param options
  103653. */
  103654. EnvironmentHelper.prototype.updateOptions = function (options) {
  103655. var newOptions = __assign({}, this._options, options);
  103656. if (this._ground && !newOptions.createGround) {
  103657. this._ground.dispose();
  103658. this._ground = null;
  103659. }
  103660. if (this._groundMaterial && !newOptions.createGround) {
  103661. this._groundMaterial.dispose();
  103662. this._groundMaterial = null;
  103663. }
  103664. if (this._groundTexture) {
  103665. if (this._options.groundTexture != newOptions.groundTexture) {
  103666. this._groundTexture.dispose();
  103667. this._groundTexture = null;
  103668. }
  103669. }
  103670. if (this._skybox && !newOptions.createSkybox) {
  103671. this._skybox.dispose();
  103672. this._skybox = null;
  103673. }
  103674. if (this._skyboxMaterial && !newOptions.createSkybox) {
  103675. this._skyboxMaterial.dispose();
  103676. this._skyboxMaterial = null;
  103677. }
  103678. if (this._skyboxTexture) {
  103679. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  103680. this._skyboxTexture.dispose();
  103681. this._skyboxTexture = null;
  103682. }
  103683. }
  103684. if (this._groundMirror && !newOptions.enableGroundMirror) {
  103685. this._groundMirror.dispose();
  103686. this._groundMirror = null;
  103687. }
  103688. if (this._scene.environmentTexture) {
  103689. if (this._options.environmentTexture != newOptions.environmentTexture) {
  103690. this._scene.environmentTexture.dispose();
  103691. }
  103692. }
  103693. this._options = newOptions;
  103694. this._setupBackground();
  103695. this._setupImageProcessing();
  103696. };
  103697. /**
  103698. * Sets the primary color of all the available elements.
  103699. * @param color the main color to affect to the ground and the background
  103700. */
  103701. EnvironmentHelper.prototype.setMainColor = function (color) {
  103702. if (this.groundMaterial) {
  103703. this.groundMaterial.primaryColor = color;
  103704. }
  103705. if (this.skyboxMaterial) {
  103706. this.skyboxMaterial.primaryColor = color;
  103707. }
  103708. if (this.groundMirror) {
  103709. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  103710. }
  103711. };
  103712. /**
  103713. * Setup the image processing according to the specified options.
  103714. */
  103715. EnvironmentHelper.prototype._setupImageProcessing = function () {
  103716. if (this._options.setupImageProcessing) {
  103717. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  103718. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  103719. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  103720. this._setupEnvironmentTexture();
  103721. }
  103722. };
  103723. /**
  103724. * Setup the environment texture according to the specified options.
  103725. */
  103726. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  103727. if (this._scene.environmentTexture) {
  103728. return;
  103729. }
  103730. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  103731. this._scene.environmentTexture = this._options.environmentTexture;
  103732. return;
  103733. }
  103734. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  103735. this._scene.environmentTexture = environmentTexture;
  103736. };
  103737. /**
  103738. * Setup the background according to the specified options.
  103739. */
  103740. EnvironmentHelper.prototype._setupBackground = function () {
  103741. if (!this._rootMesh) {
  103742. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  103743. }
  103744. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  103745. var sceneSize = this._getSceneSize();
  103746. if (this._options.createGround) {
  103747. this._setupGround(sceneSize);
  103748. this._setupGroundMaterial();
  103749. this._setupGroundDiffuseTexture();
  103750. if (this._options.enableGroundMirror) {
  103751. this._setupGroundMirrorTexture(sceneSize);
  103752. }
  103753. this._setupMirrorInGroundMaterial();
  103754. }
  103755. if (this._options.createSkybox) {
  103756. this._setupSkybox(sceneSize);
  103757. this._setupSkyboxMaterial();
  103758. this._setupSkyboxReflectionTexture();
  103759. }
  103760. this._rootMesh.position.x = sceneSize.rootPosition.x;
  103761. this._rootMesh.position.z = sceneSize.rootPosition.z;
  103762. this._rootMesh.position.y = sceneSize.rootPosition.y;
  103763. };
  103764. /**
  103765. * Get the scene sizes according to the setup.
  103766. */
  103767. EnvironmentHelper.prototype._getSceneSize = function () {
  103768. var _this = this;
  103769. var groundSize = this._options.groundSize;
  103770. var skyboxSize = this._options.skyboxSize;
  103771. var rootPosition = this._options.rootPosition;
  103772. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  103773. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103774. }
  103775. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  103776. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  103777. });
  103778. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  103779. if (this._options.sizeAuto) {
  103780. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  103781. this._scene.activeCamera.upperRadiusLimit) {
  103782. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  103783. skyboxSize = groundSize;
  103784. }
  103785. var sceneDiagonalLenght = sceneDiagonal.length();
  103786. if (sceneDiagonalLenght > groundSize) {
  103787. groundSize = sceneDiagonalLenght * 2;
  103788. skyboxSize = groundSize;
  103789. }
  103790. // 10 % bigger.
  103791. groundSize *= 1.1;
  103792. skyboxSize *= 1.5;
  103793. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  103794. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  103795. }
  103796. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103797. };
  103798. /**
  103799. * Setup the ground according to the specified options.
  103800. */
  103801. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  103802. var _this = this;
  103803. if (!this._ground || this._ground.isDisposed()) {
  103804. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  103805. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  103806. this._ground.parent = this._rootMesh;
  103807. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  103808. }
  103809. this._ground.receiveShadows = this._options.enableGroundShadow;
  103810. };
  103811. /**
  103812. * Setup the ground material according to the specified options.
  103813. */
  103814. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  103815. if (!this._groundMaterial) {
  103816. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  103817. }
  103818. this._groundMaterial.alpha = this._options.groundOpacity;
  103819. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  103820. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  103821. this._groundMaterial.primaryColor = this._options.groundColor;
  103822. this._groundMaterial.useRGBColor = false;
  103823. this._groundMaterial.enableNoise = true;
  103824. if (this._ground) {
  103825. this._ground.material = this._groundMaterial;
  103826. }
  103827. };
  103828. /**
  103829. * Setup the ground diffuse texture according to the specified options.
  103830. */
  103831. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  103832. if (!this._groundMaterial) {
  103833. return;
  103834. }
  103835. if (this._groundTexture) {
  103836. return;
  103837. }
  103838. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  103839. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  103840. return;
  103841. }
  103842. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103843. diffuseTexture.gammaSpace = false;
  103844. diffuseTexture.hasAlpha = true;
  103845. this._groundMaterial.diffuseTexture = diffuseTexture;
  103846. };
  103847. /**
  103848. * Setup the ground mirror texture according to the specified options.
  103849. */
  103850. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  103851. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103852. if (!this._groundMirror) {
  103853. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  103854. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  103855. this._groundMirror.anisotropicFilteringLevel = 1;
  103856. this._groundMirror.wrapU = wrapping;
  103857. this._groundMirror.wrapV = wrapping;
  103858. this._groundMirror.gammaSpace = false;
  103859. if (this._groundMirror.renderList) {
  103860. for (var i = 0; i < this._scene.meshes.length; i++) {
  103861. var mesh = this._scene.meshes[i];
  103862. if (mesh !== this._ground &&
  103863. mesh !== this._skybox &&
  103864. mesh !== this._rootMesh) {
  103865. this._groundMirror.renderList.push(mesh);
  103866. }
  103867. }
  103868. }
  103869. }
  103870. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  103871. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  103872. };
  103873. /**
  103874. * Setup the ground to receive the mirror texture.
  103875. */
  103876. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  103877. if (this._groundMaterial) {
  103878. this._groundMaterial.reflectionTexture = this._groundMirror;
  103879. this._groundMaterial.reflectionFresnel = true;
  103880. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  103881. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  103882. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  103883. }
  103884. };
  103885. /**
  103886. * Setup the skybox according to the specified options.
  103887. */
  103888. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  103889. var _this = this;
  103890. if (!this._skybox || this._skybox.isDisposed()) {
  103891. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  103892. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  103893. }
  103894. this._skybox.parent = this._rootMesh;
  103895. };
  103896. /**
  103897. * Setup the skybox material according to the specified options.
  103898. */
  103899. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  103900. if (!this._skybox) {
  103901. return;
  103902. }
  103903. if (!this._skyboxMaterial) {
  103904. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  103905. }
  103906. this._skyboxMaterial.useRGBColor = false;
  103907. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  103908. this._skyboxMaterial.enableNoise = true;
  103909. this._skybox.material = this._skyboxMaterial;
  103910. };
  103911. /**
  103912. * Setup the skybox reflection texture according to the specified options.
  103913. */
  103914. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  103915. if (!this._skyboxMaterial) {
  103916. return;
  103917. }
  103918. if (this._skyboxTexture) {
  103919. return;
  103920. }
  103921. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  103922. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  103923. return;
  103924. }
  103925. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103926. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  103927. this._skyboxTexture.gammaSpace = false;
  103928. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  103929. };
  103930. /**
  103931. * Dispose all the elements created by the Helper.
  103932. */
  103933. EnvironmentHelper.prototype.dispose = function () {
  103934. if (this._groundMaterial) {
  103935. this._groundMaterial.dispose(true, true);
  103936. }
  103937. if (this._skyboxMaterial) {
  103938. this._skyboxMaterial.dispose(true, true);
  103939. }
  103940. this._rootMesh.dispose(false);
  103941. };
  103942. /**
  103943. * Default ground texture URL.
  103944. */
  103945. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  103946. /**
  103947. * Default skybox texture URL.
  103948. */
  103949. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  103950. /**
  103951. * Default environment texture URL.
  103952. */
  103953. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  103954. return EnvironmentHelper;
  103955. }());
  103956. BABYLON.EnvironmentHelper = EnvironmentHelper;
  103957. })(BABYLON || (BABYLON = {}));
  103958. //# sourceMappingURL=babylon.environmentHelper.js.map
  103959. var BABYLON;
  103960. (function (BABYLON) {
  103961. /** Internal class used to store shapes for emitters */
  103962. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  103963. function ParticleSystemSetEmitterCreationOptions() {
  103964. }
  103965. return ParticleSystemSetEmitterCreationOptions;
  103966. }());
  103967. /**
  103968. * Represents a set of particle systems working together to create a specific effect
  103969. */
  103970. var ParticleSystemSet = /** @class */ (function () {
  103971. function ParticleSystemSet() {
  103972. /**
  103973. * Gets the particle system list
  103974. */
  103975. this.systems = new Array();
  103976. }
  103977. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  103978. /**
  103979. * Gets the emitter node used with this set
  103980. */
  103981. get: function () {
  103982. return this._emitterNode;
  103983. },
  103984. enumerable: true,
  103985. configurable: true
  103986. });
  103987. /**
  103988. * Creates a new emitter mesh as a sphere
  103989. * @param options defines the options used to create the sphere
  103990. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  103991. * @param scene defines the hosting scene
  103992. */
  103993. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  103994. if (this._emitterNode) {
  103995. this._emitterNode.dispose();
  103996. }
  103997. this._emitterCreationOptions = {
  103998. kind: "Sphere",
  103999. options: options,
  104000. renderingGroupId: renderingGroupId
  104001. };
  104002. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  104003. emitterMesh.renderingGroupId = renderingGroupId;
  104004. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  104005. material.emissiveColor = options.color;
  104006. emitterMesh.material = material;
  104007. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104008. var system = _a[_i];
  104009. system.emitter = emitterMesh;
  104010. }
  104011. this._emitterNode = emitterMesh;
  104012. };
  104013. /**
  104014. * Starts all particle systems of the set
  104015. * @param emitter defines an optional mesh to use as emitter for the particle systems
  104016. */
  104017. ParticleSystemSet.prototype.start = function (emitter) {
  104018. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104019. var system = _a[_i];
  104020. if (emitter) {
  104021. system.emitter = emitter;
  104022. }
  104023. system.start();
  104024. }
  104025. };
  104026. /**
  104027. * Release all associated resources
  104028. */
  104029. ParticleSystemSet.prototype.dispose = function () {
  104030. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104031. var system = _a[_i];
  104032. system.dispose();
  104033. }
  104034. this.systems = [];
  104035. if (this._emitterNode) {
  104036. this._emitterNode.dispose();
  104037. this._emitterNode = null;
  104038. }
  104039. };
  104040. /**
  104041. * Serialize the set into a JSON compatible object
  104042. * @returns a JSON compatible representation of the set
  104043. */
  104044. ParticleSystemSet.prototype.serialize = function () {
  104045. var result = {};
  104046. result.systems = [];
  104047. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  104048. var system = _a[_i];
  104049. result.systems.push(system.serialize());
  104050. }
  104051. if (this._emitterNode) {
  104052. result.emitter = this._emitterCreationOptions;
  104053. }
  104054. return result;
  104055. };
  104056. /**
  104057. * Parse a new ParticleSystemSet from a serialized source
  104058. * @param data defines a JSON compatible representation of the set
  104059. * @param scene defines the hosting scene
  104060. * @param gpu defines if we want GPU particles or CPU particles
  104061. * @returns a new ParticleSystemSet
  104062. */
  104063. ParticleSystemSet.Parse = function (data, scene, gpu) {
  104064. if (gpu === void 0) { gpu = false; }
  104065. var result = new ParticleSystemSet();
  104066. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  104067. scene = scene || BABYLON.Engine.LastCreatedScene;
  104068. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  104069. var system = _a[_i];
  104070. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  104071. }
  104072. if (data.emitter) {
  104073. var options = data.emitter.options;
  104074. switch (data.emitter.kind) {
  104075. case "Sphere":
  104076. result.setEmitterAsSphere({
  104077. diameter: options.diameter,
  104078. segments: options.segments,
  104079. color: BABYLON.Color3.FromArray(options.color)
  104080. }, data.emitter.renderingGroupId, scene);
  104081. break;
  104082. }
  104083. }
  104084. return result;
  104085. };
  104086. return ParticleSystemSet;
  104087. }());
  104088. BABYLON.ParticleSystemSet = ParticleSystemSet;
  104089. })(BABYLON || (BABYLON = {}));
  104090. //# sourceMappingURL=babylon.particleSystemSet.js.map
  104091. var BABYLON;
  104092. (function (BABYLON) {
  104093. /**
  104094. * This class is made for on one-liner static method to help creating particle system set.
  104095. */
  104096. var ParticleHelper = /** @class */ (function () {
  104097. function ParticleHelper() {
  104098. }
  104099. /**
  104100. * Create a default particle system that you can tweak
  104101. * @param emitter defines the emitter to use
  104102. * @param capacity defines the system capacity (default is 500 particles)
  104103. * @param scene defines the hosting scene
  104104. * @returns the new Particle system
  104105. */
  104106. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  104107. if (capacity === void 0) { capacity = 500; }
  104108. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  104109. system.emitter = emitter;
  104110. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  104111. system.createConeEmitter(0.1, Math.PI / 4);
  104112. // Particle color
  104113. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  104114. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  104115. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  104116. // Particle Size
  104117. system.minSize = 0.1;
  104118. system.maxSize = 0.1;
  104119. // Emission speed
  104120. system.minEmitPower = 2;
  104121. system.maxEmitPower = 2;
  104122. system.emitRate = 30;
  104123. return system;
  104124. };
  104125. /**
  104126. * This is the main static method (one-liner) of this helper to create different particle systems
  104127. * @param type This string represents the type to the particle system to create
  104128. * @param scene The scene where the particle system should live
  104129. * @param gpu If the system will use gpu
  104130. * @returns the ParticleSystemSet created
  104131. */
  104132. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  104133. if (gpu === void 0) { gpu = false; }
  104134. if (!scene) {
  104135. scene = BABYLON.Engine.LastCreatedScene;
  104136. ;
  104137. }
  104138. var token = {};
  104139. scene._addPendingData(token);
  104140. return new Promise(function (resolve, reject) {
  104141. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  104142. scene._removePendingData(token);
  104143. return reject("Particle system with GPU is not supported.");
  104144. }
  104145. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  104146. scene._removePendingData(token);
  104147. var newData = JSON.parse(data.toString());
  104148. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  104149. }, undefined, undefined, undefined, function (req, exception) {
  104150. scene._removePendingData(token);
  104151. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  104152. });
  104153. });
  104154. };
  104155. /**
  104156. * Static function used to export a particle system to a ParticleSystemSet variable.
  104157. * Please note that the emitter shape is not exported
  104158. * @param system defines the particle systems to export
  104159. */
  104160. ParticleHelper.ExportSet = function (systems) {
  104161. var set = new BABYLON.ParticleSystemSet();
  104162. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  104163. var system = systems_1[_i];
  104164. set.systems.push(system);
  104165. }
  104166. return set;
  104167. };
  104168. /**
  104169. * Gets or sets base Assets URL
  104170. */
  104171. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  104172. return ParticleHelper;
  104173. }());
  104174. BABYLON.ParticleHelper = ParticleHelper;
  104175. })(BABYLON || (BABYLON = {}));
  104176. //# sourceMappingURL=babylon.particleHelper.js.map
  104177. var BABYLON;
  104178. (function (BABYLON) {
  104179. /**
  104180. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  104181. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  104182. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  104183. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104184. */
  104185. var VideoDome = /** @class */ (function (_super) {
  104186. __extends(VideoDome, _super);
  104187. /**
  104188. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  104189. * @param name Element's name, child elements will append suffixes for their own names.
  104190. * @param urlsOrVideo defines the url(s) or the video element to use
  104191. * @param options An object containing optional or exposed sub element properties
  104192. */
  104193. function VideoDome(name, urlsOrVideo, options, scene) {
  104194. var _this = _super.call(this, name, scene) || this;
  104195. _this._useDirectMapping = false;
  104196. // set defaults and manage values
  104197. name = name || "videoDome";
  104198. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104199. options.clickToPlay = Boolean(options.clickToPlay);
  104200. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  104201. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  104202. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104203. if (options.useDirectMapping === undefined) {
  104204. _this._useDirectMapping = true;
  104205. }
  104206. else {
  104207. _this._useDirectMapping = options.useDirectMapping;
  104208. }
  104209. _this._setReady(false);
  104210. // create
  104211. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  104212. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104213. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  104214. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104215. texture.onLoadObservable.addOnce(function () {
  104216. _this._setReady(true);
  104217. });
  104218. // configure material
  104219. material.useEquirectangularFOV = true;
  104220. material.fovMultiplier = 1.0;
  104221. material.opacityFresnel = false;
  104222. if (_this._useDirectMapping) {
  104223. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104224. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104225. material.diffuseTexture = texture;
  104226. }
  104227. else {
  104228. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104229. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104230. material.reflectionTexture = texture;
  104231. }
  104232. // configure mesh
  104233. _this._mesh.material = material;
  104234. _this._mesh.parent = _this;
  104235. // optional configuration
  104236. if (options.clickToPlay) {
  104237. scene.onPointerUp = function () {
  104238. _this._videoTexture.video.play();
  104239. };
  104240. }
  104241. return _this;
  104242. }
  104243. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  104244. /**
  104245. * Gets the video texture being displayed on the sphere
  104246. */
  104247. get: function () {
  104248. return this._videoTexture;
  104249. },
  104250. enumerable: true,
  104251. configurable: true
  104252. });
  104253. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  104254. /**
  104255. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104256. * Also see the options.resolution property.
  104257. */
  104258. get: function () {
  104259. return this._material.fovMultiplier;
  104260. },
  104261. set: function (value) {
  104262. this._material.fovMultiplier = value;
  104263. },
  104264. enumerable: true,
  104265. configurable: true
  104266. });
  104267. /**
  104268. * Releases resources associated with this node.
  104269. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104270. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104271. */
  104272. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104273. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104274. this._videoTexture.dispose();
  104275. this._mesh.dispose();
  104276. this._material.dispose();
  104277. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104278. };
  104279. return VideoDome;
  104280. }(BABYLON.Node));
  104281. BABYLON.VideoDome = VideoDome;
  104282. })(BABYLON || (BABYLON = {}));
  104283. //# sourceMappingURL=babylon.videoDome.js.map
  104284. var BABYLON;
  104285. (function (BABYLON) {
  104286. /**
  104287. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  104288. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  104289. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  104290. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104291. */
  104292. var PhotoDome = /** @class */ (function (_super) {
  104293. __extends(PhotoDome, _super);
  104294. /**
  104295. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  104296. * @param name Element's name, child elements will append suffixes for their own names.
  104297. * @param urlsOfPhoto define the url of the photo to display
  104298. * @param options An object containing optional or exposed sub element properties
  104299. */
  104300. function PhotoDome(name, urlOfPhoto, options, scene) {
  104301. var _this = _super.call(this, name, scene) || this;
  104302. _this._useDirectMapping = false;
  104303. // set defaults and manage values
  104304. name = name || "photoDome";
  104305. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104306. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104307. if (options.useDirectMapping === undefined) {
  104308. _this._useDirectMapping = true;
  104309. }
  104310. else {
  104311. _this._useDirectMapping = options.useDirectMapping;
  104312. }
  104313. _this._setReady(false);
  104314. // create
  104315. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104316. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104317. // configure material
  104318. material.opacityFresnel = false;
  104319. material.useEquirectangularFOV = true;
  104320. material.fovMultiplier = 1.0;
  104321. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  104322. _this.photoTexture.onLoadObservable.addOnce(function () {
  104323. _this._setReady(true);
  104324. });
  104325. // configure mesh
  104326. _this._mesh.material = material;
  104327. _this._mesh.parent = _this;
  104328. return _this;
  104329. }
  104330. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  104331. /**
  104332. * Gets or sets the texture being displayed on the sphere
  104333. */
  104334. get: function () {
  104335. return this._photoTexture;
  104336. },
  104337. set: function (value) {
  104338. if (this._photoTexture === value) {
  104339. return;
  104340. }
  104341. this._photoTexture = value;
  104342. if (this._useDirectMapping) {
  104343. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104344. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104345. this._material.diffuseTexture = this._photoTexture;
  104346. }
  104347. else {
  104348. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104349. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104350. this._material.reflectionTexture = this._photoTexture;
  104351. }
  104352. },
  104353. enumerable: true,
  104354. configurable: true
  104355. });
  104356. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  104357. /**
  104358. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104359. * Also see the options.resolution property.
  104360. */
  104361. get: function () {
  104362. return this._material.fovMultiplier;
  104363. },
  104364. set: function (value) {
  104365. this._material.fovMultiplier = value;
  104366. },
  104367. enumerable: true,
  104368. configurable: true
  104369. });
  104370. /**
  104371. * Releases resources associated with this node.
  104372. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104373. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104374. */
  104375. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104376. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104377. this._photoTexture.dispose();
  104378. this._mesh.dispose();
  104379. this._material.dispose();
  104380. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104381. };
  104382. return PhotoDome;
  104383. }(BABYLON.Node));
  104384. BABYLON.PhotoDome = PhotoDome;
  104385. })(BABYLON || (BABYLON = {}));
  104386. //# sourceMappingURL=babylon.photoDome.js.map
  104387. var BABYLON;
  104388. (function (BABYLON) {
  104389. BABYLON.Engine.prototype.createQuery = function () {
  104390. return this._gl.createQuery();
  104391. };
  104392. BABYLON.Engine.prototype.deleteQuery = function (query) {
  104393. this._gl.deleteQuery(query);
  104394. return this;
  104395. };
  104396. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  104397. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  104398. };
  104399. BABYLON.Engine.prototype.getQueryResult = function (query) {
  104400. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  104401. };
  104402. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  104403. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104404. this._gl.beginQuery(glAlgorithm, query);
  104405. return this;
  104406. };
  104407. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  104408. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104409. this._gl.endQuery(glAlgorithm);
  104410. return this;
  104411. };
  104412. BABYLON.Engine.prototype._createTimeQuery = function () {
  104413. var timerQuery = this.getCaps().timerQuery;
  104414. if (timerQuery.createQueryEXT) {
  104415. return timerQuery.createQueryEXT();
  104416. }
  104417. return this.createQuery();
  104418. };
  104419. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  104420. var timerQuery = this.getCaps().timerQuery;
  104421. if (timerQuery.deleteQueryEXT) {
  104422. timerQuery.deleteQueryEXT(query);
  104423. return;
  104424. }
  104425. this.deleteQuery(query);
  104426. };
  104427. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  104428. var timerQuery = this.getCaps().timerQuery;
  104429. if (timerQuery.getQueryObjectEXT) {
  104430. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  104431. }
  104432. return this.getQueryResult(query);
  104433. };
  104434. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  104435. var timerQuery = this.getCaps().timerQuery;
  104436. if (timerQuery.getQueryObjectEXT) {
  104437. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  104438. }
  104439. return this.isQueryResultAvailable(query);
  104440. };
  104441. BABYLON.Engine.prototype.startTimeQuery = function () {
  104442. var caps = this.getCaps();
  104443. var timerQuery = caps.timerQuery;
  104444. if (!timerQuery) {
  104445. return null;
  104446. }
  104447. var token = new BABYLON._TimeToken();
  104448. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104449. if (caps.canUseTimestampForTimerQuery) {
  104450. token._startTimeQuery = this._createTimeQuery();
  104451. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  104452. }
  104453. else {
  104454. if (this._currentNonTimestampToken) {
  104455. return this._currentNonTimestampToken;
  104456. }
  104457. token._timeElapsedQuery = this._createTimeQuery();
  104458. if (timerQuery.beginQueryEXT) {
  104459. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104460. }
  104461. else {
  104462. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104463. }
  104464. this._currentNonTimestampToken = token;
  104465. }
  104466. return token;
  104467. };
  104468. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  104469. var caps = this.getCaps();
  104470. var timerQuery = caps.timerQuery;
  104471. if (!timerQuery || !token) {
  104472. return -1;
  104473. }
  104474. if (caps.canUseTimestampForTimerQuery) {
  104475. if (!token._startTimeQuery) {
  104476. return -1;
  104477. }
  104478. if (!token._endTimeQuery) {
  104479. token._endTimeQuery = this._createTimeQuery();
  104480. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  104481. }
  104482. }
  104483. else if (!token._timeElapsedQueryEnded) {
  104484. if (!token._timeElapsedQuery) {
  104485. return -1;
  104486. }
  104487. if (timerQuery.endQueryEXT) {
  104488. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  104489. }
  104490. else {
  104491. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  104492. }
  104493. token._timeElapsedQueryEnded = true;
  104494. }
  104495. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104496. var available = false;
  104497. if (token._endTimeQuery) {
  104498. available = this._getTimeQueryAvailability(token._endTimeQuery);
  104499. }
  104500. else if (token._timeElapsedQuery) {
  104501. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  104502. }
  104503. if (available && !disjoint) {
  104504. var result = 0;
  104505. if (caps.canUseTimestampForTimerQuery) {
  104506. if (!token._startTimeQuery || !token._endTimeQuery) {
  104507. return -1;
  104508. }
  104509. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  104510. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  104511. result = timeEnd - timeStart;
  104512. this._deleteTimeQuery(token._startTimeQuery);
  104513. this._deleteTimeQuery(token._endTimeQuery);
  104514. token._startTimeQuery = null;
  104515. token._endTimeQuery = null;
  104516. }
  104517. else {
  104518. if (!token._timeElapsedQuery) {
  104519. return -1;
  104520. }
  104521. result = this._getTimeQueryResult(token._timeElapsedQuery);
  104522. this._deleteTimeQuery(token._timeElapsedQuery);
  104523. token._timeElapsedQuery = null;
  104524. token._timeElapsedQueryEnded = false;
  104525. this._currentNonTimestampToken = null;
  104526. }
  104527. return result;
  104528. }
  104529. return -1;
  104530. };
  104531. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  104532. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  104533. };
  104534. // We also need to update AbstractMesh as there is a portion of the code there
  104535. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  104536. var engine = this.getEngine();
  104537. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  104538. this._isOccluded = false;
  104539. return;
  104540. }
  104541. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  104542. this._isOccluded = false;
  104543. return;
  104544. }
  104545. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  104546. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  104547. if (isOcclusionQueryAvailable) {
  104548. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  104549. this._isOcclusionQueryInProgress = false;
  104550. this._occlusionInternalRetryCounter = 0;
  104551. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  104552. }
  104553. else {
  104554. this._occlusionInternalRetryCounter++;
  104555. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  104556. this._isOcclusionQueryInProgress = false;
  104557. this._occlusionInternalRetryCounter = 0;
  104558. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  104559. // if strict continue the last state of the object.
  104560. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  104561. }
  104562. else {
  104563. return;
  104564. }
  104565. }
  104566. }
  104567. var scene = this.getScene();
  104568. if (scene.getBoundingBoxRenderer) {
  104569. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  104570. if (!this._occlusionQuery) {
  104571. this._occlusionQuery = engine.createQuery();
  104572. }
  104573. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  104574. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  104575. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  104576. this._isOcclusionQueryInProgress = true;
  104577. }
  104578. };
  104579. })(BABYLON || (BABYLON = {}));
  104580. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  104581. var BABYLON;
  104582. (function (BABYLON) {
  104583. /**
  104584. * Class used to generate noise procedural textures
  104585. */
  104586. var NoiseProceduralTexture = /** @class */ (function (_super) {
  104587. __extends(NoiseProceduralTexture, _super);
  104588. /**
  104589. * Creates a new NoiseProceduralTexture
  104590. * @param name defines the name fo the texture
  104591. * @param size defines the size of the texture (default is 256)
  104592. * @param scene defines the hosting scene
  104593. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  104594. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  104595. */
  104596. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  104597. if (size === void 0) { size = 256; }
  104598. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  104599. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  104600. _this._time = 0;
  104601. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  104602. _this.brightness = 0.2;
  104603. /** Defines the number of octaves to process */
  104604. _this.octaves = 3;
  104605. /** Defines the level of persistence (0.8 by default) */
  104606. _this.persistence = 0.8;
  104607. /** Gets or sets animation speed factor (default is 1) */
  104608. _this.animationSpeedFactor = 1;
  104609. _this._updateShaderUniforms();
  104610. return _this;
  104611. }
  104612. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  104613. var scene = this.getScene();
  104614. if (!scene) {
  104615. return;
  104616. }
  104617. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  104618. this.setFloat("brightness", this.brightness);
  104619. this.setInt("octaves", this.octaves);
  104620. this.setFloat("persistence", this.persistence);
  104621. this.setFloat("timeScale", this._time);
  104622. };
  104623. /** Generate the current state of the procedural texture */
  104624. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  104625. this._updateShaderUniforms();
  104626. _super.prototype.render.call(this, useCameraPostProcess);
  104627. };
  104628. /**
  104629. * Serializes this noise procedural texture
  104630. * @returns a serialized noise procedural texture object
  104631. */
  104632. NoiseProceduralTexture.prototype.serialize = function () {
  104633. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  104634. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  104635. return serializationObject;
  104636. };
  104637. /**
  104638. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  104639. * @param parsedTexture defines parsed texture data
  104640. * @param scene defines the current scene
  104641. * @param rootUrl defines the root URL containing noise procedural texture information
  104642. * @returns a parsed NoiseProceduralTexture
  104643. */
  104644. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  104645. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  104646. return texture;
  104647. };
  104648. return NoiseProceduralTexture;
  104649. }(BABYLON.ProceduralTexture));
  104650. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  104651. })(BABYLON || (BABYLON = {}));
  104652. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  104653. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\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;\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","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\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 CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\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(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\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#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","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#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\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#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform 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 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 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#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#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 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() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\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 BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*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(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\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#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\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\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\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 dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*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}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\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 int octaves;\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"};
  104654. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\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};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=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\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  104655. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  104656. globalObject["BABYLON"] = BABYLON;
  104657. //backwards compatibility
  104658. if(typeof earcut !== 'undefined') {
  104659. globalObject["Earcut"] = {
  104660. earcut: earcut
  104661. };
  104662. }
  104663. return BABYLON;
  104664. });